【发布时间】:2017-01-17 02:49:24
【问题描述】:
我正在尝试从this webpage 中获取网球比赛的结果。特别是我试图获取两名球员的姓名、日期/时间和比赛结果。我有两个问题:
默认情况下网页不会显示所有匹配项 - 这些只能通过点击页面底部的“显示更多匹配项”来显示。
当我在美丽的汤中加载 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