代码
import requests
from lxml import etree
URL = ‘http://www.chinastor.com/si/hub/list_239_2.html’
res = requests.get(URL)
res.encoding = ‘gb2312’
html = res.content.decode(‘gb2312’)
e_html = etree.HTML(html)
title = e_html.xpath(’//table[@class=“hovertable”]/tr[@onmouseover]//a[@href]/text()’)
print(title)
代码解释
1、from lxml import etree
XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 都构建于 XPath 表达之上。
导入命令:from lxml import etree
2、res.encoding = 'gb2312’和res.content.decode(‘gb2312’)
encoding:编码,decode:解码;
res.encoding直接读取源文件字节流,后方指定对该字节流的编码方案,当我们的文件编码是UTF-8时,我们encoding使用了GB2312那就会造成对字节流的编码错误,此时要替换过来,再进行指定编码;
.content.decode就是读取源文件字节流,随后将该字节流编码为Unicode编码,方便再进行更加精确的解码;
3、etree.