python用for循环一直出现最后一个值_在Python中用for循环从beautifulsoup中抓取只返回最后一个resu...

我试着用beauthoulsoup从网页上获取数据,并(最终)将其输出到csv。作为这方面的第一步,我尝试获取相关表的文本。我设法做到了这一点,但是当我重新运行代码时,代码不再给我相同的输出:当我运行for循环时,它不再返回所有12372条记录,而是保存最后一条记录。在

我的代码的缩写版本是:from bs4 import BeautifulSoup

BirthsSoup = BeautifulSoup(browser.page_source, features="html.parser")

print(BirthsSoup.prettify())

# this confirms that the soup has captured the page as I want it to

birthsTable = BirthsSoup.select('#t2 td')

# selects all the elements in the table I want

birthsLen = len(birthsTable)

# birthsLen: 12372

for i in range(birthsLen):

print(birthsTable[i].prettify())

# this confirms that the beautifulsoup tag object correctly captured all of the table

for i in range(birthsLen):

birthsText = birthsTable[i].getText()

# this was supposed to compile the text for every element in the table

但是for循环只保存表中最后一个(即12372nd)元素的文本。我是否需要做一些其他的事情,以便它在循环时保存每个元素?我想我之前的(期望的)输出在新行中包含了每个元素的文本。在

这是我第一次使用python,如果我犯了一个明显的错误,请道歉。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值