首页 > 解决方案 > 如何从不同的页面中提取表格?(Python)

问题描述

我想在 http:// 上提取第一个薮页的表格

这些表已经被下面的代码刮掉了,它们在一个列表中,从 bs4 import BeautifulSoup 导入 urllib

base_url = "http://"
url_list = ["{}?page={}".format(base_url, str(page)) for page in range(1, 21)]

mega = []
for url in url_list:
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')
    table = soup.find('table', {'class': 'table table-bordered table-striped table-hover'}) 
    mega.append(table)

因为它是一个列表,不能使用 'soup find_all' 来提取我想要的项目,所以我将它们转换为 bs4.element.Tag 以进一步搜索项目

for i in mega:
    trs = table.find_all('tr')[1:]
    rows = list()
    for tr in trs:
        rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])
rows

这些行仅提取最后一页的表格。我的代码有什么问题,所以之前的 19 个表没有被提取出来?谢谢!

这两个项目的长度不相等。我在meaga中使用for i来获得i。

len(mega) = 20
len(i) = 5

标签: python-3.xbeautifulsoup

解决方案


问题很简单。在这个 for 循环中:

for i in mega:
    trs = table.find_all('tr')[1:]
    rows = list()
    for tr in trs:
        rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])

rows = list()您在 for 循环中进行初始化。所以你循环了 21 次,但你也清空了 20 次列表。

所以你需要这样:

rows = list()
for i in mega:
    trs = table.find_all('tr')[1:]
    for tr in trs:
        rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])

推荐阅读