【问题标题】:Webscraping - with BeautifulSoup网页抓取 - 使用 BeautifulSoup
【发布时间】:2016-01-14 01:28:36
【问题描述】:

我是 beautifulsoup 的新手,我在篮球参考中使用它时遇到了麻烦。我正在尝试将 Advanced stats 的整个数据框存储到 pandas 数据框中,但我什至无法选择它。到目前为止,这是我的代码:

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


url='http://www.basketball-reference.com/teams/ATL/2016.html'
html = urlopen(url)
soup = BeautifulSoup(html)

soup.findAll('table',attrs={'id': 'advanced'})

从上面的代码中选择高级后,我看到了我需要的 html,但我实际上无法解析和提取数据。

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    找到table 元素并让read_html() 进行解析和数据帧初始化工作:

    table = soup.find('table', attrs={'id': 'advanced'})
    
    df = pd.read_html(str(table))
    print(df)  # prints a dataframe with 15 rows x 27 columns
    

    【讨论】:

    • 感谢您的回复。我收到“ImportError: html5lib not found, please install it”错误。但是我安装并导入它,但仍然出现此错误。我该怎么办?
    • @PippensPips 您可能需要安装html5lib:pip3 install html5lib 或尝试将解析器设置为bs4:df = pd.read_html(StringIO(str(table)), flavor="bs4")
    • 这些解决方案都不起作用。还有其他方法吗?
    • @PippensPips 我不知道你的设置。您只需将html5lib 模块安装到您正在执行脚本的同一python 环境中。显然,您已经以某种方式安装了BeautifulSouppandas - 这与html5lib 完全一样。
    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多