2016-04-01 20 views
0

したがって、次のコードを使用してサイトから彫像を掻き集めています。BeautifulSoupを使用してPython Webを掻き集め、ループして特定のURL値をスキップします

from bs4 import BeautifulSoup 
import requests 


f = open('C:\Python27\projects\FL_final.doc','w') 

base_url = "http://www.leg.state.fl.us/statutes/index.cfm?App_mode=Display_Statute&URL=0000-0099/00{chapter:02d}/00{chapter:02d}.html" 

for chapter in range (1,9): 
    url = base_url.format(chapter=chapter) 
    r = requests.get(url) 
    soup = BeautifulSoup((r.content),"html.parser") 
    tableContents = soup.find('div', {'class': 'Chapters' }) 
    for title in tableContents.find_all ('div', {'class': 'Title' }): 
    f.write (title.text) 

    for data in tableContents.find_all('div',{'class':'Section' }): 
     data = data.text.encode("utf-8","ignore") 
     data = "\n\n" + str(data)+ "\n" 
     f.write(data) 

f.close() 

問題は特定の章がないことです。たとえば、第1章から第2章までのページがあり、3,4,5番目のページは存在しません。だから範囲(1,9)を使用すると、彼らの(0003/0003、0004/0004、0005/0005)URLが存在しないので、3,4,5の内容を拾うことができないので、エラーが発生します。

ループ内の見つからないURLをスキップして、その範囲内で次のURLを見つける方法を教えてください。ここ

章1のURLです:tableContentsが発見された場合は、例えばを確認することができますhttp://www.leg.state.fl.us/statutes/index.cfm?App_mode=Display_Statute&URL=0000-0099/0001/0001.html

答えて

2

あなたはURL要求のためtryを追加し、find_allを適用する前tableContents is not noneいることを確認することができます。

import requests 

f = open('C:\Python27\projects\FL_final.doc','w') 

base_url = "http://www.leg.state.fl.us/statutes/index.cfm?App_mode=Display_Statute&URL=0000-0099/00{chapter:02d}/00{chapter:02d}.html" 

for chapter in range (1,9): 
    url = base_url.format(chapter=chapter) 
    try: 
    r = requests.get(url) 
    except requests.exceptions.RequestException as e: # This is the correct syntax 
     print "missing url" 
     print e 
     sys.exit(1) 
    soup = BeautifulSoup((r.content),"html.parser") 
    tableContents = soup.find('div', {'class': 'Chapters' }) 

    if tableContents is not None: 
    for title in tableContents.find_all ('div', {'class': 'Title' }): 
     f.write (title.text) 

    for data in tableContents.find_all('div',{'class':'Section' }): 
     data = data.text.encode("utf-8","ignore") 
     data = "\n\n" + str(data)+ "\n" 
     print data 
     f.write(data) 
+0

ありがとうございました!コードが動作します! try/exceptを正確に教えてください。 RequestException関数は動作しますか? – CHballer

+1

これは例外処理に関するものです(詳細はhttps://docs.python.org/2/tutorial/errors.html#handling-exceptionsを参照してください)。しかし、あなたのケースでは、問題は定義されていない 'tableContents'オブジェクトに適用された' find_all'に関連していました(章がありません)。 – SLePort

0


    tableContents = soup.find('div', {'class': 'Chapters' }) 
    if tableContents: 
     for title in tableContents.find_all ('div', {'class': 'Title' }): 
      f.write (title.text) 
関連する問題