Re: [問題] 爬蟲錯誤

看板Python作者 (swpoker)時間12年前 (2013/05/21 09:22), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串4/4 (看更多)
其實首先網頁都是stateless的 所以不能有該連線的狀態可以維持一陣子 基本當資料傳送+接收完其連線就會結束 沒辦法讓你像開個socket一樣放在那裡一值用 然後我定義好一個目的就是 我要能拿到目標資料 首先第一步就是 def getcontent(相關的連線參數->參數或是global都可以): con = 連線 rs = 得到資料 return rs 在你的主要邏輯就可以分離了 soup = BeautifulSoup(getcontect(連線參數)) 接著就可以在該getcontent增加一些東西 例如 1.如果得到資料失敗可以在試看看然後有次數的限制 def getcontect(retry = 5 , retrytime=100): exception = none for in in range(5): try: con=連線 rs = 得到資料 處理其他->或是也可放在final處理 看你摟 可以先判斷一下得到的內容是不是正確->通常有值我就當正確了然後就回傳了 if rs : return rs except XXException: exception = 處理錯誤 其他錯誤例外處理... time.sleep(retrytime) if exception : raise exception return '' -->這裡要看回傳空 還是丟出錯誤 就看你 如果要處理連線的問題 你是使用open然後read其實就是連線的時候才需要開啟 如果沒事的話該連線就會關閉 這是http +tcp/ip的特性 除非用socket 可是你連的是網站就是這樣 所以前提就是你要知道連線的特性 提供給你參考 ※ 引述《darklimit ()》之銘言: : 應用隨機休息再繼續,還是會出現這樣的錯誤 : error: [Errno 10054] 遠端主機已強制關閉一個現存的連線。 : 進行except例外處理,continue繼續的話 : 後面nameTag對應到的genre,rating 全部都會打亂 : 這樣應該要怎麼處理? : 謝謝 : for i in idlist: : headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT : 6.1;en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} : req = : urllib2.Request("http://www.imdb.com/title/tt"+i+"/",headers=headers) : try: : html = : urllib2.urlopen("http://www.imdb.com/title/tt"+i+"/",timeout = 30) : htmls = html.read() : html.close : soup = BeautifulSoup(htmls) : nameTag = [a.get_text() for a in soup.find_all("title")] : genreTag = [a.get_text() for a in : soup.find_all("span",{"itemprop":"genre"})] : ratingTag = soup.find_all("span",{"itemprop":"ratingValue"}) : for tag in nameTag: : titlelist.append(nameTag) : for tag in genreTag: : genrelist.append(genreTag) : break : for tag in ratingTag: : val = ''.join(tag.find(text=True)) : valuelist.append(val) : except HTTPError, e: : print e.code : print e.read() : #continue : except URLError, e: : print 'Reason: ', e.reason : #continue : rsleep = random.randint(10, 40) : time.sleep(rsleep) : return zip(titlelist, genrelist, valuelist) -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 163.29.28.131

05/22 17:59, , 1F
謝謝你提供的建議與想法,XD謝謝~
05/22 17:59, 1F
文章代碼(AID): #1HcinSlL (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
0
8
完整討論串 (本文為第 4 之 4 篇):
0
8
文章代碼(AID): #1HcinSlL (Python)