如何修复 "Unicode strings with encoding declaration are not supported."

How to fix "Unicode strings with encoding declaration are not supported."

ValueError: Unicode strings with encoding declaration are not supported. 
Please use bytes input or XML fragments without declaration.

当我尝试解析此站点时,它不起作用。

当我尝试序列化此页面文本时出现错误 TypeError: Type 'str' cannot be serialized

from lxml import html

source = 'http://games.chruker.dk/eve_online/item.php?type_id=814'
path = '//*[@id="top"]/table[1]/tbody/tr[1]/td[3]/table'

page = requests.get(source)
pagetext = page.text

parser = html.fromstring(pagetext)

result = parser.xpath(path)
print(result)


我希望 table 网站要求如下: http://games.chruker.dk/eve_online/item.php?type_id=814

试试这个:

parser = html.fromstring(bytes(pagetext, encoding='utf8'))

API 提供的 parse 函数允许您像在 source 变量中那样直接传入 URL:

from lxml import html

source = 'http://games.chruker.dk/eve_online/item.php?type_id=814'
path = '//*[@id="top"]/table[1]/tbody/tr[1]/td[3]/table'

tree = html.parse(source)

result = tree.xpath(path)

print(result)