python - 如何处理 IncompleteRead : in python

标签 python python-2.7 web-scraping beautifulsoup mechanize

我正在尝试从网站获取一些数据。但是它返回给我incomplete read。我要获取的数据是大量嵌套链接。我在网上做了一些研究,发现这可能是由于服务器错误(之前完成的分 block 传输编码 达到预期大小)。我还在此 link 上找到了上述解决方法

但是,我不确定如何将其用于我的情况。以下是我正在处理的代码

br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1;Trident/5.0)')]
urls = "http://shop.o2.co.uk/mobile_phones/Pay_Monthly/smartphone/all_brands"
page = urllib2.urlopen(urls).read()
soup = BeautifulSoup(page)
links = soup.findAll('img',url=True)

for tag in links:
    name = tag['alt']
    tag['url'] = urlparse.urljoin(urls, tag['url'])
    r = br.open(tag['url'])
    page_child = br.response().read()
    soup_child = BeautifulSoup(page_child)
    contracts = [tag_c['value']for tag_c in soup_child.findAll('input', {"name": "tariff-duration"})]
    data_usage = [tag_c['value']for tag_c in soup_child.findAll('input', {"name": "allowance"})]
    print contracts
    print data_usage

请帮帮我。谢谢

最佳答案

link您在问题中包含的只是一个执行 urllib 的 read() 函数的包装器,它为您捕获任何不完整的读取异常。如果你不想实现整个补丁,你总是可以在读取链接的地方抛出一个 try/catch 循环。例如:

try:
    page = urllib2.urlopen(urls).read()
except httplib.IncompleteRead, e:
    page = e.partial

对于python3

try:
    page = request.urlopen(urls).read()
except (http.client.IncompleteRead) as e:
    page = e.partial

关于python - 如何处理 IncompleteRead : in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14442222/

相关文章:

python - 如何在python中使用opencv从sftp位置读取视频文件

python - 为什么 Python 中的某些列表方法仅适用于已定义的变量?

python - 如何通过抓取从ucsc基因组浏览器中提取表浏览器结果

html - 使用 scrapy 和 css 从 HTML 中提取特定值

python - 在 python 列表中查找元组中的唯一元素

python - 设置gunicorn和django : No module named revamp. wsgi

python - django - urls.py 根路径集

python - nltk下载url授权问题

python - 将 CSV 的每一行存储为单独的列表/字典

python - 通过click()找到超链接后如何使用find_element