【问题标题】:web scraping : how to scrape one particular table body out of many table bodies?网页抓取:如何从多个表格主体中抓取一个特定的表格主体?
【发布时间】:2019-10-16 12:28:38
【问题描述】:

我正在尝试抓取网站中的特定表格 - http://stats.espncricinfo.com/ci/engine/player/35320.html?class=2;template=results;type=batting

现在,有多个彼此无法区分的表。我想从那里只刮一张特定的桌子。我该怎么做?

我尝试过使用find_all() 函数。但这只列出了所有<tbody> 标签。

我只想抓取突出显示的表格主体。

【问题讨论】:

    标签: web-scraping beautifulsoup


    【解决方案1】:

    它是 tbody 标记的,您可以将以下 css 选择器与 bs4 一起使用。然后用 table 标签包装并传递给 pandas 以很好地打印。我正在使用 bs4 4.7.1

    您也可以使用table = soup.select('tbody:contains(year)')

    Python:

    from bs4 import BeautifulSoup as bs
    import requests
    import pandas as pd
    
    r = requests.get('http://stats.espncricinfo.com/ci/engine/player/35320.html?class=2;template=results;type=batting')
    soup = bs(r.content, 'lxml')
    table = soup.select('tbody:nth-child(7)')
    headers = [item.text for item in soup.select('.headlinks th')]
    df = pd.read_html('<table>' + str(table) + '</table>')[0]
    df.columns = headers
    df = df.dropna(how = 'all', axis=0).drop(['Span',''], axis=1)
    print(df)
    

    df.head()

    【讨论】:

    • 你试过了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多