【问题标题】:Can't fetch specific content out of some complicated html elements无法从一些复杂的 html 元素中获取特定内容
【发布时间】:2019-05-08 13:29:47
【问题描述】:

我编写了一个脚本来解析网页中的一些特定内容。内容是静态的,使用请求模块我可以访问它们。问题是我希望抓取的内容在一些非传统格式的 html 元素中。

我的脚本可以抓取包含Mondays December 26th 2016 Horse Racing Tips 等的标题。单词Mondays 和年份2016 总是出现在每个标题中。

现在,我想抓取不同的比赛提示下的内容,例如Sunshine Coast Race Tips。每个Mondays下面有不止一个比赛提示。

这样的比赛提示:

Sunshine Coast Race Tips:

Race 1: 7, 5, 4, 3 - Winner (1) $1.30 Exacta $1.90 Trifecta $4.10
Race 2: 2, 4, 3, 8 - Winner (1) $3.40 Exacta $62.70 Trifecta $116.10 First 4 $158.80
Race 3: 4, 10, 5, 13 - 2nd and 4th - Loss

这是我目前的尝试:

import requests
from lxml.html import fromstring

url = "https://www.freehorseracingtipsaustralia.com/mondays-horse-racing-results-2016"

res = requests.get(url,headers={"User-Agent":"Mozilla/5.0"})
root = fromstring(res.text)
for item in root.xpath("//b[starts-with(.,'Mondays')]"):
    print(item.text_content())

我怎样才能做到这一点?

【问题讨论】:

    标签: python python-3.x xpath web-scraping


    【解决方案1】:

    尝试以下代码以获取比赛提示

    for item in root.xpath('''(//div[b/font[.="Today's Race Tips:"]])[1]/following-sibling::div/b'''):
        print(item.text_content())
    

    【讨论】:

    • 我知道只要您在线@sir Andersson,就会有希望。我还有一个要求。我想获得Mondays December 26th 2016 Horse Racing Tips 中显示的标题。
    • @asmitu ,如果您只需要第一个块的提示,请尝试更新。你是这个意思吗?
    • 不,先生。我的意思是,在包含Mondays 的多个标题中,每个标题下都有多个提示。
    • 你的 xpath 可以获取,我认为,所有的提示。我现在需要做的就是让所有标题与不同的提示相关联。
    • @asmitu ,您的意思是要在输出中包含"Mondays December 19th 2016 Horse Racing Tips:" 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多