【发布时间】:2015-10-21 04:49:32
【问题描述】:
我试图弄清楚我是否正确使用了 lxml 的 xpath 函数。这是我当前的代码,包括我们在一个相当大的抓取库中慢慢积累的所有解决方法,该库处理可怕的、可怕的输入:
import certifi, requests
from lxml import html
s = requests.session()
r = s.get(
url,
verify=certifi.where(),
**request_dict
)
# Throw an error if a bad status code is returned.
r.raise_for_status()
# If the encoding is iso-8859-1, switch it to cp1252 (a superset)
if r.encoding == 'ISO-8859-1':
r.encoding = 'cp1252'
# Grab the content
text = r.text
html_tree = html.fromstring(text)
如果这一切正常,requests 使用r.encoding 来决定在调用r.text 时如何创建一个unicode 对象。伟大的。我们获取该 unicode 对象 (text) 并将其发送到 ltml.html.fromstring(),它识别出它是 unicode,并返回给我们一个 ElementTree。
这一切似乎都正常工作,但令人不安的是,当我这样做时:
html_tree.xpath('//text()')[0]
这应该给我树中的第一个文本节点,我得到一个字符串,而不是一个 unicode 对象,我发现自己不得不写:
html_tree.xpath('//text()')[0].decode('utf8')
这太糟糕了。
我一开始所做的所有工作的全部想法是创建Mythical Unicode Sandwich,但无论我做什么,我都会得到二进制字符串。我在这里错过了什么?
这里有一个概念证明:
import certifi, requests
from lxml import html
s = requests.session()
r = s.get('https://www.google.com', verify=certifi.where())
print type(r.text) # <type 'unicode'>, GREAT!
html_tree = html.fromstring(r.text)
first_node = html_tree.xpath('//text()', smart_strings=False)[0]
print type(first_node) # <type 'str'>, TERRIBLE!
【问题讨论】:
标签: xpath unicode utf-8 lxml python-requests