gpt4 book ai didi

python - 使用 BeautifulSoup 遍历整个表格

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:34 24 4
gpt4 key购买 nike

下面的代码抓取了当前在任美国参议员的维基百科页面,该页面包含在一个表格中。目前,该代码可以为我提供来自阿拉巴马州的第一位参议员的姓名、党派等信息 - 我如何修改它以遍历整个表格?

from bs4 import BeautifulSoup
from urllib.request import urlopen

senatorwiki = 'https://en.wikipedia.org/wiki/List_of_current_United_States_Senators'
html = urlopen(senatorwiki)
soup = BeautifulSoup(html.read(), "lxml")

senatortable = soup.find('table',{'class':"sortable"})
td = senatortable.find('td')
state = td.find_next()
ns = state.find_next_sibling()
picture = ns.find_next_sibling()
name = picture.find_next_sibling()
party = name.find_next_sibling()
privsec = party.find_next_sibling()
print(state.text,ns.text,name.text,party.text,privsec.text)

最佳答案

遍历表 findAll tr​​,然后遍历其中的所有 td。当心我正在使用请求,不仅因为它很棒,而且 urllib 在 python2.7 中没有请求。

from bs4 import BeautifulSoup
import requests

senatorwiki = 'https://en.wikipedia.org/wiki/List_of_current_United_States_Senators'
html = requests.get(senatorwiki)
soup = BeautifulSoup(html.text, "lxml")
senatortable = soup.find('table',{'class':"sortable"})
rows = senatortable.findAll('tr')

for tr in rows:
print tr.findAll('td')
# to get next lines data of the list of tds is up to you ;)
# print(state.text,ns.text,name.text,party.text,privsec.text)

关于python - 使用 BeautifulSoup 遍历整个表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375870/

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