我使用lxml从网页中提取数据,但无法将结果的ElementUnicode对象转换为字符串。这是我的代码:
from lxml import html
from lxml import etree
from lxml.etree import tostring
url = 'https://www.imdb.com/title/tt5848272/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=2413b25e-e3f6-4229-9efd-599bb9ab1f97&pf_rd_r=9S5A89ZHEXE4K8SZBC40&pf_rd_s=right-2&pf_rd_t=15061&pf_rd_i=homepage&ref_=hm_otw_t0'
page = requests.get('url')
tree = html.fromstring(page.content)
a = tree.xpath('//div[@class="credit_summary_item"]/a[../h4/text() = "Directors:"]/text()')
mynewlist = []
for i in a:
b = etree.tostring(i, method="text")
mynewlist.append(b)
下面是我遇到的错误:
TypeError: Type 'lxml.etree._ElementUnicodeResult' cannot be serialized.
任何帮助都将不胜感激。
发布于 2018-11-25 11:00:06
i
变量是一个_ElementUnicodeResult
对象(一种特殊类型的字符串)。您不能将它用作tostring()
的参数。
a
变量( XPath计算的结果)是您想要的字符串列表。如果此列表的元素必须是普通字符串而不是_ElementUnicodeResult
对象,则可以使用列表理解:
newlist = [str(s) for s in a]
https://stackoverflow.com/questions/53459703
复制相似问题