创新互联Python教程:用python可以下载网页源码吗

疆括仕网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

创新互联Python教程:用python可以下载网页源码吗

python可以下载网页的源代码,使用urllib库,或者使用更为方便的requests库。

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 错误的时候,重试下载的次数。

更多学习内容,请点击python学习网。


网页标题:创新互联Python教程:用python可以下载网页源码吗
分享路径:https://www.tyhkzb.com/article/codjeji.html
在线咨询
服务热线
服务热线:028-86922220
TOP