python3 urllibWebダウンロード

Webダウンロード機能を構築する

環境: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:ダウンロードURL
user_agent:ユーザーエージェント
num_retries:再ダウンロードの回数
この関数は、WebページをダウンロードしてHTMLを返し、例外をキャッチし、サーバー側エラーのダウンロードを再試行し、ユーザーエージェントを設定します。

おすすめ

転載: blog.csdn.net/heheyangxyy/article/details/113665314
おすすめ