【问题标题】:Code outputting only one row, rather than table [duplicate]代码只输出一行,而不是表[重复]
【发布时间】:2019-02-01 16:14:41
【问题描述】:

我一直在尝试抓取包含多行和多列的表格。下面是我使用的代码,我第一次运行它时,结果符合预期,但是由于它只返回一行数据,所以列是预期的。我看不到与第一次运行相比发生了什么变化,但是我的 python 非常基础,所以我可能遗漏了一些明显的东西。

page_request = requests.get(url)    
soup = BeautifulSoup(page_request.content, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')

for row in rows:
    cols = row.find_all('td')
    cols = [x.text.strip() for x in cols]

我确信这很简单,但我们将不胜感激。

谢谢

【问题讨论】:

  • cols 的值每次循环都会被覆盖,数据对应于每一行 - 所以你之后对它所做的任何事情都只会有最后一行的数据

标签: python python-3.x


【解决方案1】:

试试这样的:

page_request = requests.get(url)    
soup = BeautifulSoup(page_request.content, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')

data = [[td.text.strip() for td in row.find_all('td')] for for row in rows]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2018-06-15
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多