我正在尝试从此页面抓取: http://www.scoresway.com/?sport=basketball&page=match&id=45926
但获取某些数据时遇到困难。
页面上的第二个表包含主队得分。评分分为“基本”和“高级”统计数据。此代码打印主队的“基本”总统计数据。
from BeautifulSoup import BeautifulSoup
import requests
gameId = 45926
url = 'http://www.scoresway.com/?sport=basketball&page=match&id=' + str(gameId)
r = requests.get(url)
soup = BeautifulSoup(r.content)
for x in soup.findAll('table')[1].findAll('tr')[-1].findAll('td'):
print ''.join(x.findAll(text=True))
如果您想查看“高级”统计信息,请单击“高级”“链接”,它会显示该统计信息,同时让您保持在同一页面上。我也想抓取这些信息,但不知道如何获取它。
最佳答案
有一个针对高级
选项卡的单独请求。对其进行模拟并使用 BeautifulSoup
进行解析。
例如,下面是打印表中所有玩家的代码:
import requests
from bs4 import BeautifulSoup
ADVANCED_URL = "http://www.scoresway.com/b/block.teama_people_match_stat.advanced?has_wrapper=true&match_id=45926&sport=basketball&localization_id=www"
response = requests.get(ADVANCED_URL)
soup = BeautifulSoup(response.text)
print [td.text.strip() for td in soup('td', class_='name')]
打印:
[u'T. Chandler *',
u'K. Durant *',
u'L. James *',
u'R. Westbrook',
...
u'C. Anthony']
如果您查看 ADVANCED_URL
,您会发现网址 GET 参数中唯一的“动态”部分是 match_id
和 sport
参数。如果您需要使代码可重用并适用于网站上类似的其他页面,则需要动态填充 match_id
和 sport
。实现示例:
from bs4 import BeautifulSoup
import requests
BASE_URL = 'http://www.scoresway.com/?sport={sport}&page=match&id={match_id}'
ADVANCED_URL = "http://www.scoresway.com/b/block.teama_people_match_stat.advanced?has_wrapper=true&match_id={match_id}&sport={sport}&localization_id=www"
def get_match(sport, match_id):
# basic
r = requests.get(BASE_URL.format(sport=sport, match_id=match_id))
soup = BeautifulSoup(r.content)
for x in soup.findAll('table')[1].findAll('tr')[-1].findAll('td'):
print ''.join(x.findAll(text=True))
# advanced
response = requests.get(ADVANCED_URL.format(sport=sport, match_id=match_id))
soup = BeautifulSoup(response.text)
print [td.text.strip() for td in soup('td', class_='name')]
get_match('basketball', 45926)
关于javascript - Python Beautifulsoup 抓取包含 Javascript 的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941642/