有的时候,需要把整个 HTML 节点原封不动地取下来,也就是包括节点标签、节点内容,甚至也包括内容中的空格、各种特殊符号等等。

假设已获取到页面源码,并将其保存在变量 src 中。则可有代码如下:


from html import unescape
from lxml import etree
from lxml import html


# 先加载页面源码,便于后续使用 XPath 解析
root = etree.HTML(src)

# 根据 XPath 路径提取节点
script = root.xpath('//script')[-1]

# 关键的一步:把整个节点转为字符串
raw_tab = html.tostring(script)

# 此时 print(raw_tab) 会遇到中文乱码(其实不是乱码,是另一种编码显示了)的情况,需要使用 unescape
json_str = json.loads(raw_tab)
print(unescape(json_str['$meta']['cityName']))

# 如果本身不是 json 字符串,则因为 unescape 函数接收的是 bytes-like 对象,所以需要先 decode
print(unescape(raw_tab.decode()))

相关文章:

  • 2021-09-18
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
相关资源
相似解决方案