我有大約3000個網址,其中一些工作,而其中一些沒有。我嘗試運行美麗的湯,但我得到了一些不同的錯誤,這使我困惑 - 我不知道什麼樣的嘗試,除了塊我應該放在我的代碼。我想要做的是忽略所有內部服務器錯誤的URL,只能使用那些沒有錯誤的文件,並獲取下面代碼中寫入的文本。如何刮蟒蛇與旁路錯誤
我的代碼:
mega = [[]] # list in a list
for i in range(len(ab)): # ab as a dictionary with multiple keys
... myurl = soc[i]['the_urls']
... html = urllib2.urlopen(myurl).read()
... soup = BeautifulSoup(html, "html.parser")
... row = soup.findAll('tr')
... for r in row:
... mega.append([r.get_text()]) # scrape all the texts
錯誤:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 473, in error
return self._call_chain(*args)
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/Users/name/anaconda/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Internal Server Error
是否錯誤意味着所有網址都具有同樣的問題 - 內部服務器錯誤?在這種情況下,我想我能做的一個方法是包含一個try和except塊,它表示如果沒有http錯誤500,則嘗試嘗試,如果有,則傳遞。
編輯:
我試着用下面的代碼繞過錯誤,我不知道它是否工作,特別是如果「合格」或「繼續」做正確的事:
for i in range(len(soc)):
... myurl = soc[i]['report_url']
... while True:
... try:
... html = urllib2.urlopen(myurl).read()
... break
... except urllib2.HTTPError:
... continue
... soup = BeautifulSoup(html, "html.parser")
... row = soup.findAll('tr')
... for r in row:
... mega.append([r.get_text()]) # scrape the text
不,它實際上意味着一個URL返回500錯誤。你應該用'try' /'except'來處理它。 –
您在上述註釋中的代碼是不可讀的。 –
您的編輯將循環,直到通話成功。可能是永遠的。 –