使用Python爬取网页内容并保存
使用urllib方法、requests爬取
使用urllib方法、requests爬取特别简单,有时候有些网站会有反爬技术,就需要伪装浏览器去访问,然后再爬取。
import urllib.request import requests url="https://www.bilibili.com/" #有些网站会现在,但可伪装浏览器爬取 浏览器User-Agent的详细信息(可采用下面的进行爬虫伪装) #浏览器头信息代理可以直接搜Http Header之User-Agent,以下是谷歌浏览器的 headers={
"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0" } #使用伪装浏览器的urllib方法 def use_urllib_Liu(url): req = urllib.request.Request(url,headers=headers) response = urllib.request.urlopen(req) data = response.read().decode() print(data) #使用urllib方法 def use_urllib(url): response = urllib.request.urlopen(url) data = response.read().decode() print(data) #使用#requests方法 def use_requests(url): #实践发现,request不用headers也可以爬到设了防爬限制的网站 #response = requests.get(url) # 使用伪装浏览器的urllib方法 response = requests.get(url,headers=headers) data = response.text print(data) if __name__ == '__main__': #use_urllib_Liu(url) #use_urllib(url) use_requests(url)
使用requests方法爬取并保存
话不多说直接上 代码片.
import urllib.request import requests url="https://www.bilibili.com/" #有些网站会现在,但可伪装浏览器爬取 浏览器User-Agent的详细信息(可采用下面的进行爬虫伪装) #浏览器头信息代理可以直接搜Http Header之User-Agent,以下是谷歌浏览器的 headers={
"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0" } #使用requests方法 def use_requests(url,headers): #实践发现,request不用headers也可以爬到设了防爬限制的网站 #response = requests.get(url) # 使用伪装浏览器的urllib方法 response = requests.get(url,headers=headers) data = response.text #print(data) file_path="E:/Python/bilibili/bilibili.html" #将爬到的内容保存到本地 with open(file_path,"w",encoding="utf-8") as f: f.write(data) if __name__ == '__main__': use_requests(url,headers)
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214879.html原文链接:https://javaforall.net
