无法访问div内部的表格(basketballreference)

时间:2019-04-27 23:26:12

标签: python web-scraping beautifulsoup

我目前正在编写一个Python脚本,部分脚本从2005年至2015年的NBA选秀中每个球员职业生涯的前四个赛季中获得了收益。我已经花了将近2个小时来解决这个问题(越来越多感到沮丧),但我一直无法获得单个玩家的胜利份额。我正在尝试使用以下链接中的“高级”表作为测试用例:https://www.basketball-reference.com/players/b/bogutan01.html#advanced::none

从草稿页获取播放器的名称时,我没有遇到任何问题,但是我尝试了以下代码的多次迭代,并且无法成功访问统计信息所在的td元素。

playerSoup = BeautifulSoup(playerHtml)
        playertr = playerSoup.find_all("table", id = "advanced").find("tbody").findAll("tr")
        playerws = playertr.findAll("td")[21].getText()

1 个答案:

答案 0 :(得分:1)

此页面使用JavaScript添加表,但不从服务器读取数据。所有表格均为HTML,但为注释<!-- ... ->

使用BeautifulSoup可以找到所有注释,然后检查哪个注释包含文本"Advanced"。然后,您可以在BeautifulSoup

中将该注释用作普通HTML
import requests
from bs4 import BeautifulSoup
from bs4 import Comment

url = 'https://www.basketball-reference.com/players/b/bogutan01.html#advanced::none'

r = requests.get(url)

soup = BeautifulSoup(r.content)

all_comments = soup.find_all(string=lambda text: isinstance(text, Comment))

for item in all_comments:
    if "Advanced" in item:
        adv = BeautifulSoup(item)

        playertr = adv.find("table", id="advanced")

        if not playertr:
            #print('skip')
            continue # skip comment without table - go back to `for`

        playertr = playertr.find("tbody").findAll("tr")
        playerws = adv.find_all("td")[21].getText()

        print('playertr:', playertr)
        print('playerws:', playerws)

        for row in playertr:
            if row:
                print(row.find_all('th')[0].text)
                all_td = row.find_all('td')
                print([x.text for x in all_td])
                print('--')