2016-05-21 9 views
-1

私はPythonを初めて使い、最近私のプロジェクト用のウェブサイトからデータを収集するためのWebクローヤを作成しようとしています。データの量はかなり大きいため、収集に時間がかかります。その間、私はいくつかの問題に出会った:Python Web Clawer:クローワをよりうまく動作させる方法

    502悪いゲートウェイ - 私はそれで何ができますか?

  1. 私はtry... expect...を使用して例外を処理しますが、プログラムは例外によって中断されているようですが、プログラムを中断することなくすべての例外を処理するにはどうすればよいですか?

本当に助けてくれてありがとう!

は私のコードです:(Pythonの2.7、BeautifulSoup4.3.2、XlsxWriter0.8.7)

# coding: utf-8 
import urllib2 
import urllib 
import re 
from bs4 import BeautifulSoup 
import urlparse 
import xlsxwriter 
import traceback; 

def open_with_retries(url): 
attempts = 5 
for attempt in range(attempts): 
    try: 
     return opener.open(url) 
    except: 
     if attempt == attempts - 1: 
      raise 

workbook = xlsxwriter.Workbook('Artist_Art_B.xlsx') 
worksheet = workbook.add_worksheet() 

ro = 0 
co = 0 

opener = urllib2.build_opener() 
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6')] 

# First web 
response = open_with_retries(unicode("http://amma.artron.net/artronindex_artist.php")) 
content = response.read() 
pattern = re.compile(u'<li><a href="artronindex_pic.php(.*?) title="(.*?)".*?</a></li>',re.S) 
items = re.findall(pattern,content) 
for item in items: 
    # Second 
    try: 
     res2 = open_with_retries(str("http://amma.artron.net/artronindex_pic.php?artist="+item[1])) 
     soup = BeautifulSoup(res2.read()) 
     tables = soup.find_all('tbody') 
     if len(tables)>0: 
      table = tables[0] 
      rows = table.findChildren('tr') 
      print item[1] 
      for row in rows: 
       links = row.find_all('a',href=True) 
       for link in links: 
        url = link['href'] 
        parsed = urlparse.urlparse(url) 
        sort = urlparse.parse_qs(parsed.query)['sort'][0] 
        labe = urlparse.parse_qs(parsed.query)['labe'][0] 
        f = {'sort':sort,'labe':labe} 
        later = urllib.urlencode(f) 

        # Third 
        res3 = open_with_retries(str("http://amma.artron.net/artronindex_auctionseason.php?name="+item[1]+"&"+later)) 
        soup2 = BeautifulSoup(res3.read()) 
        ttables = soup2.findChildren('tbody') 
        if len(tables)>0: 
         ttable = ttables[0] 
         rrows = ttable.findChildren('tr') 
         for rrow in rrows: 
          ccells = rrow.findChildren('td') 
          for ccell in ccells: 
           vvalue = unicode(ccell.string) 
           worksheet.write(ro,co,vvalue) 
           co=co+1 
           print vvalue 
         ro = ro+1 
         co = 0 
    except Exception: 
     traceback.print_exc() 
workbook.close() 
+0

あなたの質問は答えがあまりにも一般的です...良い答えを得るには、壊れた特定のコードを含める必要があります。 – miraculixx

+0

@miraculixxこんにちは、コードを追加しました。お礼を言わせていただきありがとうございます –

+0

このコードは実行されません。より良い質問を書くのに役立つ[このツール](https://github.com/alexmojaki/askso)を試してみてください。 –

答えて

0

(1)私は502が再試行要求することで解決できます一時的なエラーがあると推測しています。この関数の呼び出しでopener.openへの呼び出しを置き換えます。

def open_with_retries(url): 
    attempts = 5 
    for attempt in range(attempts): 
     try: 
      return opener.open(url) 
     except: 
      if attempt == attempts - 1: 
       raise 

(2)あなたは既にプログラムがこのコードで完全に停止しないことを保証しています

for item in items: 
    try: 
     ... 
    except ValueError: 
     ... 

場合にのみ機能しますがスローされる例外は、型がValueErrorです。ループは次のitemに進み、動作し続けます。 item内のできるだけ多くのlinkが処理されるように、同じパターンをfor link in linksに付けることができます。

+0

ありがとうございました!私はコードを変更し、 "ValueError"を "Exception"に変更しました。今私はそれがうまく動作するかどうかを確認するために実行している、それがうまくいくことを願って:) –

関連する問題