gpt4 book ai didi

Python 继续循环

转载 作者:行者123 更新时间:2023-11-28 22:53:22 25 4
gpt4 key购买 nike

我正在使用本教程中的以下代码 (http://jeriwieringa.com/blog/2012/11/04/beautiful-soup-tutorial-part-1/)。

from bs4 import BeautifulSoup

soup = BeautifulSoup (open("43rd-congress.html"))

final_link = soup.p.a
final_link.decompose()

trs = soup.find_all('tr')

for tr in trs:
for link in tr.find_all('a'):
fulllink = link.get ('href')
print fulllink #print in terminal to verify results

tds = tr.find_all("td")

try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error.
names = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string.
years = str(tds[1].get_text())
positions = str(tds[2].get_text())
parties = str(tds[3].get_text())
states = str(tds[4].get_text())
congress = tds[5].get_text()

except:
print "bad tr string"
continue #This tells the computer to move on to the next item after it encounters an error

print names, years, positions, parties, states, congress

但是,我收到一条错误消息,指出第 27 行的循环中“continue”不正确。我正在使用 notepad++ 和 windows powershell。如何使此代码工作?

最佳答案

print fulllink 开始的一切都在 for 循环之外

for tr in trs:
for link in tr.find_all('a'):
fulllink = link.get ('href')
## indented here!!!!!
print fulllink #print in terminal to verify results

tds = tr.find_all("td")

try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error.
names = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string.
years = str(tds[1].get_text())
positions = str(tds[2].get_text())
parties = str(tds[3].get_text())
states = str(tds[4].get_text())
congress = tds[5].get_text()

except:
print "bad tr string"
continue #This tells the computer to move on to the next item after it encounters an error

print names, years, positions, parties, states, congress

关于Python 继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485961/

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