-1

次のコードを使用すると。

from bs4 import BeautifulSoup
import csv
soup = BeautifulSoup (open("43rd-congress.htm"))

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


f = csv.writer(open("43rd_congress_all.csv", "w"))
f.writerow(["Name","Years","Position","Party", "State", "Congress", "Link"])
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
        f.writerow([names, years, posiitons, parties, states, congress, fullLink])

NameError が発生します。ただし、エラーを修正しようとすると、コードの最後の行で、変数が未定義であるというエラーが表示されます。コミュニティと共に現在の状態になるように修正を加えました。どうすれば修正できますか?

私はあなたの助けに感謝します。

これをnotepad ++とpowershellで実行しています。私はここでこのチュートリアルの最後のセクションにいます... http://jeriwieringa.com/blog/2012/11/04/beautiful-soup-tutorial-part-1/

4

2 に答える 2

2

names, years, posiitons, parties, states, congresstry/except句の最初の行でエラーが発生した場合、作成されません。

何が起こっているかというと、try構造中にエラーが発生したことです。names = str(tds[0].get_text())エラーを作成するとしましょう。あなたはそれをキャッチしますが、後者の変数は作成されません。

try/exceptたとえば、の前にデフォルト値を作成することを検討したい場合がありますnames = ''


あなたのインデント エラーは、コードが私には問題ないように見えるため、タブとスペースが混在していることが原因である可能性があります。

于 2013-10-21T05:11:46.880 に答える