如何只使用BeautifulSoup获取维基百科页面上所有表格第一行的数据?

问题描述 投票:0回答:1

我正在尝试从this维基百科页面中获取数据。

以下是我目前使用的代码。

码:

from bs4 import BeautifulSoup
import urllib.request

def make_soup(url):
    thepage = urllib.request.urlopen(url)
    soupdata = BeautifulSoup(thepage, "html.parser")
    return soupdata

soup = make_soup("https://en.wikipedia.org/wiki/2015_in_hip_hop_music")
albumdatasaved = ""
for record in soup.findAll('tr'):
    albumdata = ""
    for data in record.findAll('td'):
        albumdata = albumdata + "," + data.text
    albumdatasaved = albumdatasaved + "\n" + albumdata[1:]

print(albumdatasaved)

我只需要每个表的第一行数据,如下图所示。我怎么能这样做?

table

python web-scraping beautifulsoup wikipedia
1个回答
0
投票

这里是您的问题的完整工作代码,使用API​​是更好的方法,但我知道您需要一个快速的解决方案...

from bs4 import BeautifulSoup
import urllib.request


def make_soup(url):
    thepage = urllib.request.urlopen(url)
    soupdata = BeautifulSoup(thepage, "html.parser")
    return soupdata

soup = make_soup("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")

albumdatasaved = ""
for record in soup.findAll('tr'):
    for data in record.findAll('td'):
        if data.text.strip() and data.text[0] == ".":
            albumdatasaved += data.text.strip() + "\n"
            break

print(albumdatasaved)
© www.soinside.com 2019 - 2024. All rights reserved.