【问题标题】:Retrieving information from wiki table using XPath in Python在 Python 中使用 XPath 从 wiki 表中检索信息
【发布时间】:2020-05-18 08:38:22
【问题描述】:

我正在尝试使用 xpath 从首都 wiki 页面中检索国家名称,特别是从城市的主要信息表中。

例如我想从https://en.wikipedia.org/wiki/Barcelona检索“西班牙”

xml format for Barcelona table country row

Barcelona information table

网址是http://en.wikipedia.org/wiki/Barcelona

import requests
import lxml.html

res = requests.get(url)
doc = lxml.html.fromstring(res.content)
country = doc.xpath("//table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow']//th[contains(text(), 'Country')]/td//a//text()")

没有得到任何结果

谢谢

【问题讨论】:

    标签: python-3.x xpath


    【解决方案1】:

    tr 包含 thtd 作为兄弟,因此将 th 签入谓词:

    //table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow'][th = 'Country']/td//a//text()
    

    当我跑步时

    import requests
    import lxml.html
    
    url = 'https://en.wikipedia.org/wiki/Barcelona'
    
    res = requests.get(url)
    doc = lxml.html.fromstring(res.content)
    
    country = doc.xpath("//table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow'][th = 'Country']/td//a//text()")
    
    print(country)
    

    它输出['Spain']

    由于有些条目没有链接,我认为使用xpath("string(//table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow'][th = 'Country']/td)") 更容易。

    【讨论】:

    • 谢谢,但它仍然不适用于 en.wikipedia.org/wiki/Barcelona 它适用于其他城市,例如 en.wikipedia.org/wiki/Berlin 不明白为什么
    • @Jackson,你能告诉我们你使用的 Python 代码吗?请编辑问题并将其插入其中。
    • @Jackson,我已经尝试过您的 Python 代码,在打印 country 变量时,我得到了输出 ['Spain']。那么当您说“仍然无法正常工作”时,您究竟会得到哪个结果或错误?
    • 对不起,我错了,我检查时可能错过了一个字符或其他东西。但是由于某种原因,它并没有针对en.wikipedia.org/wiki/Basel 这样的所有情况进行处理,我不知道为什么会发生这种情况,谢谢
    • 巴塞尔的那个条目没有链接到国家,所以你可能更想要xpath("string(//table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow'][th = 'Country']/td)")。这将直接在 Python 变量 country 中为您提供一个字符串,而不是带有字符串的列表。
    【解决方案2】:

    更短的形式:

    normalize-space(//th[@scope][.="Country"]/following-sibling::td)
    

    输出:Spain

    【讨论】:

    • 所以它确实找到了“Spain”,但对于 en.wikipedia.org/wiki/Basel 它没有找到“Switzerland”
    • 好的。您已经有了解决方案,但我已经编辑了答案。
    猜你喜欢
    • 2011-02-05
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2015-04-27
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多