python模拟浏览器爬取数据

时间:2022-05-27 10:20:19

爬虫新手大坑:爬取数据的时候一定要设置header伪装成浏览器!!!!

在爬取某财经网站数据时由于没有设置Header信息,直接被封掉了ip

后来设置了Accept、Connection、User-Agent三个参数后换了个ip登录,成功请求到几次数据后又被封掉ip

最后老老实实把所有header信息都加上后请求(其实还少了一个cookie),现在请求了几十次还没被封     (ಥ﹏ಥ)

代码如下

#coding=utf-8
import requests
from bs4 import BeautifulSoup headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip,deflate,sdch',
'Accept-Language':'en,zh-CN;q=0.8,zh;q=0.6',
'Cache-Control':'max-age=0',
'Host':'www.xxx.com', #此处为财经网的主页
'Connection':'keep-alive',
'Upgrade-Insecure-Requests':'',
'Content-Type':'application/x-www-form-urlencoded',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36'
}
response = requests.get("http://www.xxxxxx.com", headers=headers) #请求的地址
soup = BeautifulSoup(response.content, 'html.parser') #返回的html信息用soup解析
print(response.status_code) #请求状态码
print(soup.prettify())  #以格式输出html
有不懂的地方或者想要探讨问题可以qq联系:1163949417