python访问网站函数

一般我们爬取一些简单的静态网页是通过获取网页全部源代码,然后再通过正则解析出我们自己需要的数据。

所以我们一般可以写好一个向网站发起请求的方法,作为一个函数,在写其他爬虫的时候可以直接应用。

下面是我的源代码

def askURL(url):
    head = {   #伪装请求头,模拟浏览器访问
       "User-Agent":" Mozilla / 5.0(Linux;Android6.0;Nexus5 Build / MRA58N) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 99.0.4844.51Mobile Safari / 537.36"
    }
    request = urllib.request.Request(url,headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
        #print(html)
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)
    return html  #返回爬到所有的html数据

这个是直接可以使用的,参数就是你要访问的目的网址

posted @ 2022-05-07 20:28  权。  阅读(181)  评论(0)    收藏  举报