【问题标题】:How to extract only the n-nth HTML title tag in a sequence in Python with BeautifulSoup?如何使用 BeautifulSoup 在 Python 中仅提取序列中的第 n 个 HTML 标题标签?
【发布时间】:2020-05-20 14:46:58
【问题描述】:

我正在尝试从 Wikipedia 表格 (https://en.wikipedia.org/wiki/NBA_Most_Valuable_Player_Award) 中提取有关 NBA 历史上 MVP 得主的数据。

这是我的代码:

wik_req = requests.get("https://en.wikipedia.org/wiki/NBA_Most_Valuable_Player_Award")
wik_webpage = wik_req.content
soup = BeautifulSoup(wik_webpage, "html.parser")

my_table = soup('table', {"class":"wikitable plainrowheaders sortable"})[0].find_all('a')
print(my_table)

for x in my_table:
  test = x.get("title")
  print(test)

但是,此代码会打印表格的所有 HTML 标题标签,如下所示(短版):

'1955–56 NBA season
Bob Pettit
Power Forward (basketball)
United States
St. Louis Hawks
1956–57 NBA season
Bob Cousy
Point guard
Boston Celtics'

最后,我想创建一个 pandas 数据框,在其中我将所有赛季年份存储在一个列中,将所有玩家年份存储在一个列中,依此类推。仅打印一个 HTML 标签标题(例如仅 NBA 赛季年份)的诀窍是什么代码?然后我可以将它们存储到一个列中来设置我的数据框,并对球员、位置、国籍和球队做同样的事情。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    该数据框只需要:

    import pandas as pd
    
    url = "https://en.wikipedia.org/wiki/NBA_Most_Valuable_Player_Award"
    df=pd.read_html(url)[5]
    

    输出:

    print(df)
         Season                  Player  ...    Nationality                       Team
    0   1955–56             Bob Pettit*  ...  United States            St. Louis Hawks
    1   1956–57              Bob Cousy*  ...  United States             Boston Celtics
    2   1957–58           Bill Russell*  ...  United States         Boston Celtics (2)
    3   1958–59         Bob Pettit* (2)  ...  United States        St. Louis Hawks (2)
    4   1959–60       Wilt Chamberlain*  ...  United States      Philadelphia Warriors
    ..      ...                     ...  ...            ...                        ...
    59  2014–15          Stephen Curry^  ...  United States  Golden State Warriors (2)
    60  2015–16      Stephen Curry^ (2)  ...  United States  Golden State Warriors (3)
    61  2016–17      Russell Westbrook^  ...  United States  Oklahoma City Thunder (2)
    62  2017–18           James Harden^  ...  United States        Houston Rockets (4)
    63  2018–19  Giannis Antetokounmpo^  ...         Greece        Milwaukee Bucks (4)
    [64 rows x 5 columns]
    

    如果您真的想坚持使用 BeautifulSoup,下面是一个帮助您入门的示例:

    my_table = soup('table', {"class":"wikitable plainrowheaders sortable"})[0]
    
    season_col=[]
    for row in my_table.find_all('tr')[1:]:
        season = row.findChildren(recursive=False)[0]
        season_col.append(season.text.strip())
    

    我预计各列之间可能存在一些差异,但正如您所表示的您想熟悉 BeautifulSoup,这是供您探索的 :)

    【讨论】:

    • 谢谢,这肯定有帮助。但是,我正在尝试熟悉 BeautifulSoup,所以如果我也知道如何在那里处理它会很棒。有什么想法吗?
    • 添加了一个示例,如果您想使用 BeautifulSoup 并获取各个列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2022-11-10
    • 2014-05-22
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多