解决TypeError: Type 'list' cannot be serialized.

拿到HTML网页

html = etree.HTML(content)

编写规则

html = etree.HTML(content)
divs = html.xpath('//div[@class="rank"]//span[@class="span"]')
print(type(divs))
print(divs)

divs返回一个列表,无法直接打印出数据:

<class 'list'>
[<Element span at 0x16d2edb2848>]

etree.HTML():构造了一个XPath解析对象并对HTML文本进行自动修正。
etree.tostring():输出修正后的结果,类型是bytes

html = etree.HTML(content)
divs = html.xpath('//div[@class="rank"]//span[@class="span"]')
d = etree.tostring(divs,encoding='utf-8').encode('utf-8')
print(d)

报错:TypeError: Type ‘list’ cannot be serialized.

Traceback (most recent call last):
  File "E:/pycharm2019/Test/test.py", line 14, in <module>
    d = etree.tostring(divs)
  File "src/lxml/etree.pyx", line 3443, in lxml.etree.tostring
TypeError: Type 'list' cannot be serialized.

翻了很多都没有找到同样问题的解决,于是突然想起规则末尾加 /text()

html = etree.HTML(content)#HTML网页
divs = html.xpath('//div[@class="rank"]//span[@class="span"]/text()')#XPATH提取数据
print(divs)#输出数据

直接得到目标数据(根本不需要那句etree.tostring…被视频教程误导了)

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值