【问题标题】:When scraping data from basketball-reference how come certain tables are commented out?当从篮球参考中抓取数据时,某些表格是如何被注释掉的?
【发布时间】:2018-04-11 03:41:35
【问题描述】:

我正在尝试使用 BeautifulSoup 收集球员的所有篮球参考数据。让我们以迈克尔乔丹为例:https://www.basketball-reference.com/players/j/jordami01.html。问题是当我抓取 html 页面并解析 html 时,我只能抓取一个数据表,而其他数据似乎被注释掉了。我对 python 很陌生,希望有人能告诉我为什么 html 似乎有某些数据表作为 cmets。有人可以指导我解决方法吗?

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import pandas as pd

MJ_url = 'https://www.basketball-reference.com/players/j/jordami01.html'

uClient = uReq(MJ_url)

MJ_html = uClient.read()

uClient.close()

MJ_soup = soup(MJ_html, "html.parser")

MJ_containers = MJ_soup.findAll("table",{"class":"row_summable sortable 
stats_table"})

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    试试这个。 cmets中的所有数据现在都通过了:

    import requests
    from bs4 import BeautifulSoup, Comment
    
    res = requests.get("https://www.basketball-reference.com/players/j/jordami01.html",headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(res.text, 'lxml')
    for comment in soup.find_all(string=lambda text:isinstance(text,Comment)):
        data = BeautifulSoup(comment,"lxml")
        for items in data.select("table.row_summable tr"):
            tds = [item.get_text(strip=True) for item in items.select("th,td")]
            print(tds)
    

    【讨论】:

    • 您使用 requests 包而不是 urllib 有什么特别的原因吗?还有,为什么要使用 lxml 的 HTML 解析器而不是 Python HTML 解析器?
    • 无论您选择urllib 还是requests,都没有什么大不了的。我使用了requests,因为我觉得它很舒服。如果您关注this link,您可以看到解析器之间的区别。谢谢。
    猜你喜欢
    • 2021-04-18
    • 2018-07-24
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多