【问题标题】:Using Python to scrape data from web xhr feed使用 Python 从 web xhr feed 中抓取数据
【发布时间】:2017-01-17 02:49:24
【问题描述】:

我正在尝试从this webpage 中获取网球比赛的结果。特别是我试图获取两名球员的姓名、日期/时间和比赛结果。我有两个问题:

  1. 默认情况下网页不会显示所有匹配项 - 这些只能通过点击页面底部的“显示更多匹配项”来显示。

  2. 当我在美丽的汤中加载 html 时,数据似乎不存在。看起来它正在被某种查询('http://d.flashscore.com/x/feed/f_')加载,但我不确定如何直接运行它。

我的代码示例如下:

url="http://www.scoreboard.com/au/tennis/wta-singles/australian-open-2016/results/"

from urllib.request import Request, urlopen
req = Request(url, headers={"X-Fsign": "SW9D1eZo"})
s = urlopen(req,timeout=50).read()
s=urlopen(req, timeout=50).read()
soup=BeautifulSoup(s, "lxml")

match_times=soup.find_all("td", class_="cell_ad time")
players=soup.find_all("span", class_="padl"
results=soup.find_all("td", class_"cell_sa score  bold"
#these all return empty element sets

如何加载所有结果都可见的页面?我怎样才能优雅地提取上述数据?

编辑: 在建议使用 selenium 之后,我构建了一个函数,该函数将使用 Selenium/Chrome 加载页面,然后将 html 发送到 bs4:

def open_url(url):
    try:
        from urllib.request import Request, urlopen
        req = Request(url)
        s = urlopen(req,timeout=20).read()
        driver.get(url)
        try:
            driver.find_element_by_xpath("""//*[@id="tournament-page-results-more"]/tbody/tr/td/a""").click()
            time.sleep(5)
        except:
            print("No more results to show...")
        body=driver.find_element_by_id("fs-results")
        return BeautifulSoup(body.get_attribute("innerHTML"), "lxml")
    except:
        print("Webpage doesn't exist")

这意味着我可以显示所有结果,但单击显示更多按钮。不幸的是,代码在页面正确加载之前继续运行,因此当我尝试抓取所有包含结果的行时:

matches=[]
soup=open_url(url)
rrows=soup.find_all("tr")
for rrow in rrows:
    if rrow.attrs['class']!=['event_round']:
        matches.append(rrow)

它只得到最初可见的结果。我该如何解决这个问题?

【问题讨论】:

    标签: python python-3.x urllib bs4


    【解决方案1】:

    这个页面使用JavaScript来获取数据,如果你使用urllib,你只会得到没有数据的html代码。

    使用 Selenium 抓取 JS 页面。

    【讨论】:

    • 你可以提供一个例子 - 我对 Selenium 一点也不熟悉
    • 已调整代码以使用 selenium(见上文)。仍然有问题 - 在代码继续之前页面没有完成加载......
    • @user3725021 您应该发布新问题让社区解决您的问题,并接受我的回答以关闭此问题。
    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多