Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 遍历整个表格

2025年05月04日17soundcode

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

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)