【问题标题】:How to extract tables from different pages? (python)如何从不同的页面中提取表格? (Python)
【发布时间】:2020-01-25 09:41:01
【问题描述】:

我想提取http://上的第一个服务页面的表格

这些表格已被下面的代码抓取,它们在一个列表中, 导入 urllib 从 bs4 导入 BeautifulSoup

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

【问题讨论】:

  • 考虑添加 html 本身而不是链接。人们可能不喜欢访问陌生的网站。

标签: python-3.x beautifulsoup


【解决方案1】:

问题很简单。 在这个 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')])

您在 for 循环中初始化 rows = list()。所以你循环了 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')])

【讨论】:

  • 现在输出中有二十个表。但它们都是最后一张桌子,并且重复了 20 次。为什么它不搜索 1-19 表?谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-01-21
  • 2021-03-25
  • 1970-01-01
  • 2021-10-24
  • 2021-11-14
  • 2022-10-18
  • 2020-11-22
  • 1970-01-01
相关资源
最近更新 更多