gpt4 book ai didi

python - 如何从表格中抓取第二列

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:46 25 4
gpt4 key购买 nike

我试图从表的第二列中抓取数据,但失败了...

这是我的代码:

import bs4
import requests
url = "https://en.wikipedia.org/wiki/List_of_postcode_districts_in_the_United_Kingdom"`

data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')
My_table = soup.find('table',{'class':'wikitable sortable'})
#print(My_table)
My_row = My_table.find_all('tr')
#print(My_row[1])
for row in My_row:
data= (row.find('td')[1].text)
print(data)

这是错误:

TypeError: 'int' object is not subscriptable

最好的解决方案是什么?

最佳答案

这段代码似乎可以工作

import bs4
import requests

url = "https://en.wikipedia.org/wiki/List_of_postcode_districts_in_the_United_Kingdom"

data = requests.get(url)
soup = bs4.BeautifulSoup(data.text, 'html.parser')
table = soup.find('table', {'class': 'wikitable sortable'})
rows = table.find_all('tr')
for i, row in enumerate(rows):
if i > 0:
for j, td in enumerate(row.children):
if j == 3:
print(td.text.strip())

关于python - 如何从表格中抓取第二列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com