
用于网站爬图 代码太多,贴关键部分,应该问题就出自以下爬虫部分:
for i in soup1.find_all("input", type="image"): imgnow = time.strftime("%Y%m%d%H%M%S") imgurl = i['data-src'] rname = imgurl .split('/')[-1] opener = urllib.request.build_opener() opener.addheaders = self.UA urllib.request.install_opener(opener) try: #就是卡这里不动了,没有任何动静,程序静止了 urllib.request.urlretrieve( imgurl, "./Pic/%s" % imgnow + "_" + str(rname)) except Exception as e: print("出错了:%s,继续..." % e) continue 1 a7a2 2018-06-10 20:32:46 +08:00 需要加入超时处理,免得在对方网站限制或关闭时候有反应 |
3 bihuchao 2018-06-10 20:44:59 +08:00 You can read this. ref: https://stackoverflow.com/questions/8763451/how-to-handle-urllibs-timeout-in-python-3. Or you can try requests. |
4 ThirdFlame 2018-06-10 20:50:23 +08:00 推荐 requests。 当然了 不管用啥 都得考虑超时 |
5 wsds OP @ThirdFlame 加了超时,现在可以抛出异常了,但老是有这种,放在 try 了,10 个请求,有 5 个就是这种,遇到就 pass 了继续。。。。: [WinError 10054] 远程主机强迫关闭了一个现有的连接。,继续... 要么就干脆直接报错程序 终止了: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None)) |
6 ThirdFlame 2018-06-10 21:17:14 +08:00 @wsds ConnectionReset,对端发了 reset。原因很多,网络不好 对方等待超时,对方发现你再爬虫,所以超时。 各种原因。 想要仔细分析原因 抓包分析,看看是网络不好,还是对方主动的。 |
7 wsds OP @ThirdFlame 换了网络,不像是网络问题,总之感觉爬的很费力,各种异常,try 都 try 不住 |
8 SimbaPeng 2018-06-10 21:41:34 +08:00 via Android 必须要 ip 代理 |
9 herozhang 2018-06-10 21:59:08 +08:00 python 有个叫做 retry 的库,可以试一下,很方便的。 |
10 mumbler 2018-06-10 22:06:02 +08:00 要加重试机制,任何网络都会不稳定,对方服务器也可能出现故障,屏蔽等情况 |
12 Leigg 2018-06-10 22:33:18 +08:00 via iPhone 骚年,你得学会 requests。 你说的假死问题应该出在你的代码上,好好排查。 |
13 alvin666 2018-06-10 22:34:37 +08:00 via Android 为什么不用 requests ? requests.get(timeout=10) |
15 wsds OP @Leigg 请求地址用的就是 requests,只不过下载图片用的是 urllib.request.urlretrieve |
16 beforeuwait 2018-06-14 17:13:14 +08:00 我以前抓携程的时候也遇到这种问题 程序就假死在那了。 后来,我做了一个断点续爬来解决这个问题。 |