如何访问一篇博文
- 人工访问博文,有两种方式,点网页上对应博文的链接,或输入该博文的网址;
- 用爬虫访问,和人工类似,也有两种方式,可以用点击超链接的方式,也可以通过网址访问:
结合我们的需求,不难看出,应该使用网址方式访问博文。
具体的实现
- requests.get的语法
– requests.get(url,kwargs),
– url是我们想要访问的链接,kwargs是可选参数,包括params、data、json、headers、cookies、auth、files、timeout、proxies、stream、verify、cert等。 - 这里我们以支付宝及微信打赏方式这篇博客为例来进行说明。
方法1、最基本的方式
- requests.get使用默认参数:
import requests
req = requests.get("https://qxhgd.blog.csdn.net/article/details/113447691")
text=req.content.decode('utf-8')
print(text)
方法2、增加headers
-
headers有很多种,这里仅以User-Agent为例来说明;
-
为何使用User-Agent:
– 是识别浏览器的一串字符串,相当于浏览器的身份证,在利用爬虫爬取网站数据时,频繁更换User-Agent可以避免触发相应的反爬机制。 -
如何获取User-Agent:
– 具体的headers可通过前面文章提到的chrome或firefox浏览器,抓包获取,User-Agent也不例外;
– User-Agent除了上面浏览器抓取外,也可以通过后文参考资料获取不同浏览器的信息;
– 可使用python的fake_useragent库,可返回一个随机的ua请求头;l
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"
}
req = requests.get("https://qxhgd.blog.csdn.net/article/details/113447691",headers=headers)
text=req.content.decode('utf-8')
print(text)
方法3、增加proxy
-
为何使用代理服务器:
– 同一个IP访问网页如果太频繁,可能会被服务器限制;
– 更换IP,可保护自己,也为了提高爬虫的效率,防止反爬; -
如何获取代理服务器:
– 自己搭建:一般考虑搭建代理IP池;
– 网上白嫖:一般质量参差不齐,需要甄别;
– 付费资源:网上很多收费的代理服务器,一般使用购买后分配的key通过restful api接口进行获取;
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"
}
proxy = {"http": "http://121.228.8.93:8118"}
req = requests.get("https://qxhgd.blog.csdn.net/article/details/113447691",headers=headers,proxies=proxy)
text=req.content.decode('utf-8')
print(text)
参考资料
- User Agent String.Com
如本文对你有些许帮助,欢迎打赏:
支付宝及微信打赏方式