gpt4 book ai didi

python - 尝试让 lxml 在 python 中打印特定数字

转载 作者:行者123 更新时间:2023-12-01 03:45:49 24 4
gpt4 key购买 nike

我正在尝试让 lxml 打印 python 中的所选内容: /image/OlnBn.jpg

我的代码不多,但在这里

from lxml import html
import requests


page = requests.get('https://www.pathofexile.com/forum/view-thread/1703834')
tree = html.fromstring(page.content)

winner = tree.xpath(//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7])

print,winner

最佳答案

您看到的语法错误是因为您没有将 XPath 字符串括在引号中,请修复它:

winner = tree.xpath('//*[@id="eventView0"]/div[3]/table/tbody/tr[1]/td[7]')

实际问题是表格内容是通过在浏览器中执行的 JavaScript 动态形成的。你能做的就是解析 script在 JSON 对象中包含所需数据的标签,提取 JSON 字符串并通过 json.loads() 将其加载到 Python 数据结构中:

import json
import re

from lxml import html
import requests


page = requests.get('https://www.pathofexile.com/forum/view-thread/1703834')
tree = html.fromstring(page.content)

script = tree.xpath('//script[contains(., "var json")]/text()')[0]
obj_string = re.search(r"var json = (\{.*?\}),$", script, re.MULTILINE).group(1)
obj = json.loads(obj_string)

# print entries
entries = obj['ladder']['entries']
for entry in entries:
print(entry['account']['name'])

打印帐户名称(只是作为其正常工作的证明):

Havoc6
Steelmage
Olecgolec
...
Anafobia
nokieka2
HoGji

关于python - 尝试让 lxml 在 python 中打印特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com