【问题标题】:Reload Webpage when timeout Mechanize超时时重新加载网页
【发布时间】:2015-08-13 00:36:30
【问题描述】:

大家好,我的代码主要用于检查我提供的一些链接,以在网页中查找某些标签。一旦找到它,它就会把我给的链接还给我。但是,除非我设置了超时,否则有时机械化会在尝试打开/阅读页面时永远卡住。他们有没有办法在超时时重新加载/重试网页?

import mechanize
from mechanize import Browser
from bs4 import BeautifulSoup
import urllib2
import time
import os
from tqdm import tqdm
import socket


br = Browser()

with open("url.txt", 'r+') as f:
lines = f.read().splitlines()

br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

no_stock = []
for i in tqdm(lines):
    r = br.open(i, timeout=200)
    r = r.read()
    done = False
    tries = 3
    while tries and not done:
        try:
            soup = BeautifulSoup(r,'html.parser')
            done = True # exit the loop
        except:
            tries -= 1 # to exit when tries == 0
    if not done:
        print('Failed for {}'.format(i))
        continue # skip this and continue with the next
    table = soup.find_all('div', {'class' : "empty_result"})
    results = soup.find_all('strong', style = 'color: red;')
    if table or results:
        no_stock.append(i)

更新错误:

  File "/usr/local/lib/python2.7/dist-packages/mechanize/_response.py", line 190, in read
    self.__cache.write(self.wrapped.read())
  File "/usr/lib/python2.7/socket.py", line 355, in read
    data = self._sock.recv(rbufsize)
  File "/usr/lib/python2.7/httplib.py", line 587, in read
    return self._read_chunked(amt)
  File "/usr/lib/python2.7/httplib.py", line 656, in _read_chunked
    value.append(self._safe_read(chunk_left))
  File "/usr/lib/python2.7/httplib.py", line 702, in _safe_read
    chunk = self.fp.read(min(amt, MAXAMOUNT))
  File "/usr/lib/python2.7/socket.py", line 384, in read
    data = self._sock.recv(left)
socket.timeout: timed out

感谢任何帮助!

【问题讨论】:

    标签: python python-2.7 mechanize


    【解决方案1】:

    捕获socket.timeout 异常并在那里重试:

    try:
        # first try
        soup = BeautifulSoup(r,'html.parser')
    except socket.timeout:
        # try a second time
        soup = BeautifulSoup(r,'html.parser')
    

    你甚至可以尝试多次,如果一行失败,继续下一条:

    for i in tqdm(lines):
        r = br.open(i, timeout=200)
        r = r.read()
        done = False
        tries = 3
        while tries and not done:
            try:
                soup = BeautifulSoup(r,'html.parser')
                done = True # exit the loop
            except: # just catch any error
                tries -= 1 # to exit when tries == 0
        if not done:
            print('Failed for {}'.format(i))
            continue # skip this and continue with the next
        table = soup.find_all('div', {'class' : "empty_result"})
        results = soup.find_all('strong', style = 'color: red;')
        if table or results:
            no_stock.append(i)
    

    【讨论】:

    • 感谢您的回复,我对python还是很陌生。我以前想到过你的想法,并用 try 语句查找了套接字超时,但我不知道如何在超时发生时将它与我的“for”语句结合起来。愿意提供一些指导吗?
    • @Jeof,看看新的例子,我觉得更像你需要的,程序不会因为错误而停止,并且可以多次重试每一行。
    • 感谢您的提示,我已尝试再次运行它。过了一会儿,我遇到了这个错误,我刚刚在上面更新了
    • 我已经删除了错误以捕获任何东西,现在它产生了不同的结果,我已经更新了我的帖子让你看看
    • 可能是其中一行的 URL 格式不正确。希望我的回答对您最初的问题有所帮助。
    猜你喜欢
    • 2014-12-03
    • 2021-11-13
    • 2017-06-22
    • 2012-05-21
    • 1970-01-01
    • 2017-09-13
    • 2018-02-07
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多