如何修改它以遍历整个表格

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)