您的位置:首页 > 编程语言 > Python开发

python 爬虫-1:下载网页源代码

2017-08-07 09:42 218 查看
下载静态网页源代码的 python 爬虫函数源代码:

import urllib2
def download(url, num_retries = 5):
'''
function: 下载网页源代码,如果遇到 5xx 错误状态,则继续尝试下载,直到下载 num_retries 次为止。
'''
print "downloading " , url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print "download error: " , e.reason
html = None
if num_retries > 0:
if hasattr(e,'code') and 500 <= e.code < 600:
return download(url, num_retries-1)

return html


其中 url 即为你想现在的网页地址。 num_reties 为遇到 5xx 错误的时候,重试下载的次数。

具体详见我的博客:

www.wangs0622.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫 源代码
相关文章推荐