作者timTan (用口头禅区分年记)
看板Python
标题Re: [问题] 爬虫错误
时间Mon May 20 18:37:20 2013
※ 引述《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()
# And Sleep Here for every connection.
except HTTPError, e:
#Hnalde the error,
#Break,
#最好在此把你处理过的资料记下来,安心上路,下次再来
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: 118.160.190.62
1F:→ qwertmn:直觉点就递回防呆八.. 05/19 22:30
2F:→ darklimit:那应该要怎麽解决才好? 05/20 01:09
3F:→ swpoker:把连线跟处理分开两个方法~然後使用 05/20 12:58
4F:→ darklimit:所以id连结到网址是一个fun,进行处理是另一个fun吗? 05/20 15:38
5F:→ darklimit:不要将连结跟处理放在同一个fun,意思是这样吗? 05/20 15:39
6F:→ darklimit:这样程式码应该要怎麽修正? 05/20 15:44
7F:→ darklimit:连结是因为有网址,也是因为网址才有tag进行处理 05/20 15:51
8F:→ darklimit:要分开成两个function 不太了解怎麽修正 05/20 15:52
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.42.51.172
9F:→ timTan:大概写了我的想法,错误处理 博大精深! 05/20 18:38
10F:→ darklimit:原来如此,谢谢提供的建议,学到不少~ 05/22 17:57