【问题标题】:Python iteration over table with beautifulsoup gives only first column用beautifulsoup对表进行Python迭代只给出第一列
【发布时间】:2021-06-14 00:08:47
【问题描述】:

感谢 stackoverflow 上的许多帖子,我找到了许多接近我的解决方案的方法,但似乎我总是遇到同样的问题。我只得到表格的第一列

目标: This URL这里只有一张桌子,我想刮一下

这是我的代码:

# 1. get the html doc 
source = requests.get("www.placeholder.com").text

# 2. get the BeautifulSoup object
soup = bs.BeautifulSoup(source, 'lxml')

# 3. find the table
find_class = soup.table
tbody_1 = find_class.tbody


n = 1
m = 1
for row in tbody_1.find_all('tr'):
    for col in row.find_all('td'):
        if col == "Tag":
            print(col)
            print(n)
            print(m)
            print("Tags will be passed")
            pass
        else:
            if n < 13:
                value_list = []
                value_list.append(col)
                print(col)
                print(n)
                print(m)
                val_dict[m] = value_list
                n = n+1
                # m = m
            else:
                value_list = []                
                value_list.append(col)
                print(col)
                print(n)
                print(m)
                val_dict[m+1] = value_list
                n = 1
                m = m+1

这给了我以下问题: Tags

使用:

value_list.append(col.select('span')[0].get_text())

导致以下问题: First Item。 这里只使用了每行的第一项

灵感来自(答案)尤其是this link

for row in table.find_all('tr'):
    for col in row.find_all('td'):

除了我提供的内容之外,我会在需要时编辑帖子。

【问题讨论】:

  • It's scrape not scrap,因为scrap意味着摆脱为no足够长的时间。
  • 谢谢,会编辑
  • 你想要的输出是什么?整张桌子?
  • 是的整张桌子
  • 我想我迷失了许多实现它的方法,但不知何故没有把它们做对

标签: python beautifulsoup


【解决方案1】:

如果您想要的只是桌子,那么我建议您探索pandas 并让您的(刮擦)生活更轻松。

方法如下:

import pandas as pd
import requests

source_url = "https://www.placeholder.com"
page = requests.get(source_url).text
df = pd.read_html(page, flavor="bs4")
pd.concat(df).to_csv("demographischer_statistik.csv", index=False)

这会输出一个.csv 文件,如下所示:

如果你喜欢所谓的one-liners,上面的代码可以有效地简化为:

import pandas as pd
import requests

pd.concat(pd.read_html(requests.get("https://placeholder.com").text, flavor="bs4")).to_csv("demographischer_statistik.csv", index=False)

但如果你问我,那不是太可读。 ;)

【讨论】:

  • 天哪...这太简单了...非常感谢您的快速回复,这绝对有很大帮助
  • 如果您觉得我的回答有用,请考虑阅读stackoverflow.com/help/someone-answers
  • 我将构建一个循环来遍历多个页面,因此单行将非常适合其他项目,但不适合这里:)
猜你喜欢
  • 2014-10-02
  • 1970-01-01
  • 2018-06-11
  • 2022-01-18
  • 2022-08-18
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
相关资源
最近更新 更多