爬虫(一):python requests库模拟浏览器请求网页

在大家用爬虫请求数据时会有一下情况,或者直接的403,这是读取访问被禁止!

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

这时我们需要模拟浏览器来请求(我使用的是谷歌)
爬虫(一):python requests库模拟浏览器请求网页

import requests

url = 'http://www.whatismyip.com'  #请求地址

headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}#创建头部信息


response =  requests.get(url,headers = headers)  #发送网络请求


print(response.content.decode('utf-8'))#以字节流形式打印网页源码

这里我请求的这个网址是来测IP的网址