【问题标题】:How to get element text in an anchor using lxml and requests?如何使用 lxml 和请求在锚点中获取元素文本?
【发布时间】:2019-01-27 23:21:52
【问题描述】:

我正在研究 python 请求,现在我需要知道如何使用 xpath 解析 html

我从 Antica 收到了 xpath https://www.tibia.com/community/?subtopic=worlds

这是我现在的代码。

r = requests.get(U'https://www.tibia.com/community/?subtopic=worlds')
tree = html.fromstring(r.content)
worlds = tree.xpath('/html/body/div[3]/div[1]/div[2]/div/div[2]/div/div[1]/div[2]/div[5]/div/div/div/table/tbody/tr/td/div/table/tbody/tr[2]/td/div[2]/div/table/tbody/tr[2]/td[1]/a/text()')
print(worlds)

我试图找回 text"Antica",但 xpath 函数返回给我一个空列表。

【问题讨论】:

  • 看漂亮的网页解析汤

标签: python tree python-requests lxml


【解决方案1】:

我会推荐使用漂亮的汤,因为它更容易。

无论如何,如果你仍然想用 lxml 来做,你可以尝试类似的东西

r = requests.get(U'https://www.tibia.com/community/?subtopic=worlds')
tree = html.fromstring(r.content)
all_worlds = tree.xpath('/html/body//tr/td/a/@href')
for url in all_worlds:
    print(url)

【讨论】:

  • 太棒了,我将 @href 更改为 /title() 并获得了世界的标题。我去看看漂亮的肥皂,谢谢。
猜你喜欢
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多