python3 urllib网页下载

构建一个网页下载函数

环境:python3,模块:python内置模块urllib

import urllib.request
import urllib.error

def get_html(url,user_agent='xxx',num_retries):
    headers = {
    
    'User-agent':user_agent}  #设置默认用户代理
    request = urllib.request.Request(url=url,headers=headers)  #添加请求头参数
    try:
        return urllib.request.urlopen(url=request).read().decode('utf-8')
    except urllib.error.URLError as e:
        print('Error:', e.reason) #抛出异常reason
        html = None
        if num_retries > 0:
        #4xx错误发生在请求存在问题时,5xx错误发生在服务器端存在问题时。只需保证在5xx时重新下载
            if hasattr(e, 'code') and  500 <= e.code < 600:# hasattr() 函数用于判断对象是否包含对应的属性。
                return download(url,user_agent,num_retries-1)
        return html

注释:
url:下载网址
user_agent:用户代理
num_retries:重试下载次数
该函数下载网页并返回HTML,捕获异常,对服务器端错误进行重试下载,设置用户代理。

猜你喜欢

转载自blog.csdn.net/heheyangxyy/article/details/113665314