我的xpath表达式有什么问题?

2024-06-16 13:54:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取td中类为u-ctitle的所有链接。你知道吗

import os
import urllib
import lxml.html
down='http://v.163.com/special/opencourse/bianchengdaolun.html'
file=urllib.urlopen(down).read()
root=lxml.html.document_fromstring(file)
namelist=root.xpath('//td[@class="u-ctitle"]/a')
len(namelist)

输出是[],有那么多td的classis是“u-ctitle”,有了firebug你就可以得到,为什么提取不出来呢?你知道吗

enter image description here
我的python版本是2.7.9。
enter image description here

把文件改成别的名字是没有用的。你知道吗

enter image description here


Tags: importcomhttpos链接htmlrooturllib
1条回答
网友
1楼 · 发布于 2024-06-16 13:54:51

您的XPath是正确的。这个问题是无关的。你知道吗

如果检查HTML,您将看到以下元标记:

<meta http-equiv="Content-Type" content="text/html; charset=GBK" />

在这个代码中:

file=urllib.urlopen(down).read()
root=lxml.html.document_fromstring(file)

file实际上是一个字节序列,因此从GBK编码的字节到Unicode字符串的解码在document_fromstring方法中进行。你知道吗

问题是,HTML编码实际上不是GBK,lxml错误地对其进行解码,导致数据丢失。你知道吗

>>> file.decode('gbk')
Traceback (most recent call last):
  File "down.py", line 9, in <module>
    file.decode('gbk')
UnicodeDecodeError: 'gbk' codec can't decode bytes in position 7247-7248: illegal multibyte sequence

经过反复试验,我们可以发现实际的编码是GB_18030。要使脚本正常工作,需要手动解码字节:

root=lxml.html.document_fromstring(file.decode('GB18030'))

相关问题 更多 >