【问题标题】:Python scraping's trouble in extract valuePython抓取在提取价值方面的麻烦
【发布时间】:2019-05-05 21:41:32
【问题描述】:

我正在尝试从该站点的表中提取值:https://www.geonames.org/search.html?q=&country=IT

在我的示例中,我想提取名称“Rome”并使用以下代码:

import requests
import lxml.html

html = requests.get('https://www.geonames.org/search.html?q=&country=IT')
doc = lxml.html.fromstring(html.content)

table_body = doc.xpath('//*[@id="search"]/table')[0]

cities = table_body.xpath('//*[@id="search"]/table/tbody/tr[3]/td[2]/a[1]/text()')

对我来说一切都很好,但是当我打印它时,结果是:

>>> print(cities)
[]

我真的不知道可能是什么问题,有人有什么建议吗?

【问题讨论】:

标签: python-3.x xpath python-requests lxml.html


【解决方案1】:

如果您想获取"Rome",可以省略tbody。此元素是由浏览器插入的,并且不存在于请求返回的原始文档中。

另外,额外的table_body = doc.xpath('//*[@id="search"]/table')[0] 是多余的——你可以直接从根目录搜索。

import requests
import lxml.html

html = requests.get('https://www.geonames.org/search.html?q=&country=IT')
doc = lxml.html.fromstring(html.content)
print(doc.xpath('//*[@id="search"]/table/tr[3]/td[2]/a[1]/text()')[0]) # => Rome

【讨论】:

    【解决方案2】:

    这是提取该页面中所有城市的简单脚本

    import requests
    import lxml.html
    
    html = requests.get('https://www.geonames.org/search.html?q=&country=IT')
    doc = lxml.html.fromstring(html.content)
    # corrected the xpath in the below line.
    cities = doc.xpath("//table[@class='restable']//td[a][2]/a[1]/text()")
    for city in cities:
        print(city)
    

    【讨论】:

    • 非常感谢,真的很有帮助:)
    • 如果您认为问题已解决,请点击我的答案左侧的否决按钮下方的复选标记来接受答案。随意投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多