爬虫之代理和cookie的处理
代理操作
- 代理的目的
- 为解决ip被封的情况
- 什么是代理
- 代理服务器:fiddler
- 为什么使用代理可以改变请求的ip
- 本机的请求会先发送给代理服务器,代理服务器会接受本机发送过来的请求(当前请求对应的ip就是本机ip),然后代理服务器会将该请求进行转发,转发之后的请求对应的ip就是代理服务器的ip。
- 提供免费代理的平台
- www.goubanjia.com
- 快代理
- 西祠代理
- 代理精灵:http://http.zhiliandaili.cn
- 代理ip的匿名度
- 透明:使用了透明的代理ip,则对方服务器知道你当前发起的请求使用了代理服务器并且可以监测到你真实的ip
- 匿名:知道你使用了代理服务器不知道你的真实ip
- 高匿:不知道你使用了代理服务器也不知道你的真实ip
- 代理ip的类型
- http:该类型的代理IP只可以转发http协议的请求
- https:只可以转发https协议的请求
代理的测试
#代理测试
import requests
from lxml import etree
import random
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
#构建一个简易的ip池,字典形式的
proxy_list = [
{'https':'212.64.51.13:8888'},
{'https':'212.64.51.13:8888'},
{'https':'212.64.51.13:8888'},
]
url = 'https://www.baidu.com/s?ie=UTF-8&wd=ip'
#proxies指定代理ip
page_text = requests.get(url=url,headers=headers,proxies=random.choice(proxy_list)).text
with open('ip.html','w',encoding='utf-8') as fp:
fp.write(page_text)
如何构建一个标准的代理ip池
- 1.取各大平台中爬取大量的免费代理ip
- 2.校验出可用的代理ip
- 使用每一个代理ip进行请求发送,监测响应状态码是否为200
- 3.将可用的代理ip进行存储(redis)
爬取西祠 的代理ip
import requests
from lxml import etree
import random
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
} all_ips = []
# 从代理精灵上买去的代理ip
ip_url = 'http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=53&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson='
page_text = requests.get(ip_url,headers=headers).text
tree = etree.HTML(page_text)
ip_list = tree.xpath('//body//text()')
# 取出所有的代理ip并组成列表
for ip in ip_list:
ip = {'https':ip}
all_ips.append(ip) url = 'https://www.xicidaili.com/nn/%d'
for page in range(1,100):
print('正在爬取第{}页的数据!'.format(page))
new_url = format(url%page)
page_text = requests.get(url=new_url,headers=headers,proxies=random.choice(all_ips)).text
tree = etree.HTML(page_text)
tr_list = tree.xpath('//*[@id="ip_list"]//tr')[1:]
for tr in tr_list:
ip = tr.xpath('./td[2]/text()')[0]
port = tr.xpath('./td[3]/text()')[0]
ip_type = tr.xpath('./td[6]/text()')[0] dic = {
'ip':ip,
'port':port,
'type':ip_type
}
all_ips.append(dic) print(len(all_ips))
cookie的操作
- Cookie
- 什么是cookie?
- 保存在客户端的键值对
- 什么是cookie?
- 爬取雪球网中的新闻数据:https://xueqiu.com/
#通过抓包工具捕获的基于ajax请求的数据包中提取的url
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20343389&count=15&category=-1'
json_data = requests.get(url=url,headers=headers).json()
print(json_data) {'error_description': '遇到错误,请刷新页面或者重新登录帐号后再试', 'error_uri': '/v4/statuses/public_timeline_by_category.json', 'error_data': None, 'error_code': ''}
cookie的破解方式
- 手动处理:
- 通过抓包工具将请求携带的cookie添加到headers中
- 弊端:cookie会有有效时长,cookie还是动态变化
- 自动处理:
- 使用session进行cookie的自动保存和携带,代价有点大
- session是可以进行请求发送的,发送请求的方式和requests一样
- 如果使用session进行请求发送,在请求的过程中产生了cookie,则该cookie会被自动存储到session对象中
- 如果使用了携带cookie的session再次进行请求发送,则该次请求就时携带cookie进行的请求发送
#创建一个session对象
session = requests.Session()
#将cookie保存到session对象中
first_url = 'https://xueqiu.com/'
session.get(url=first_url,headers=headers)#为了获取cookie且将cookie存储到session中 url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20343389&count=15&category=-1'
json_data = session.get(url=url,headers=headers).json()#携带cookie发起的请求
pprint(json_data)
验证码的识别
验证码的识别
- 超级鹰:http://www.chaojiying.com/about.html
- 使用流程:
- 注册:用户中心身份的账号
- 登陆:
- 充值一块
- 创建一个软件:软件ID-》生成一个软件ID
- 下载示例代码:下载基于python的示例代码
- 使用流程:
- 云打码:http://www.yundama.com/demo.html
下面代码使用云打码上下载的
import requests
from hashlib import md5 class Chaojiying_Client(object): def __init__(self, username, password, soft_id):
self.username = username
password = password.encode('utf8')
self.password = md5(password).hexdigest()
self.soft_id = soft_id
self.base_params = {
'user': self.username,
'pass2': self.password,
'softid': self.soft_id,
}
self.headers = {
'Connection': 'Keep-Alive',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
} def PostPic(self, im, codetype):
"""
im: 图片字节
codetype: 题目类型 参考 http://www.chaojiying.com/price.html
"""
params = {
'codetype': codetype,
}
params.update(self.base_params)
files = {'userfile': ('ccc.jpg', im)}
r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
return r.json() def ReportError(self, im_id):
"""
im_id:报错题目的图片ID
"""
params = {
'id': im_id,
}
params.update(self.base_params)
r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
return r.json()
# 将文件进行报存
def getCodeImgText(imgPath,imgType):
chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '')#用户中心>>软件ID 生成一个替换 96001
im = open(imgPath, 'rb').read()#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
return chaojiying.PostPic(im,imgType)['pic_str']
#古诗文网的验证码识别操作
url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
page_text = requests.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
print(img_src)
img_data = requests.get(url=img_src,headers=headers).content
with open('codeImg.jpg','wb') as fp:
fp.write(img_data)
#进行验证码的识别
getCodeImgText('codeImg.jpg',1004)
模拟登陆
s = requests.Session()
#模拟登陆
#古诗文网的验证码识别操作
url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
page_text = s.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = s.get(url=img_src,headers=headers).content
with open('codeImg.jpg','wb') as fp:
fp.write(img_data) #解析动态变化的请求参数
__VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//input[@id="__VIEWSTATEGENERATOR"]/@value')[0]
print(__VIEWSTATE,__VIEWSTATEGENERATOR)
#进行验证码的识别
code_text = getCodeImgText('codeImg.jpg',1004)
print(code_text)
login_url = 'https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fcollect.aspx'
data = {
#下面两个请求参数是动态变化
#通长情况下动态变化的请求参数会被隐藏在前台页面中
'__VIEWSTATE': __VIEWSTATE,
'__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR,
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email': 'www.zhangbowudi@qq.com',
'pwd': 'bobo328410948',
'code': code_text,
'denglu': '登录',
}
#登陆成功之后对应的首页页面源码
main_page_text = s.post(url=login_url,headers=headers,data=data).text
with open('./main.html','w',encoding='utf-8') as fp:
fp.write(main_page_text)
爬虫之代理和cookie的处理的更多相关文章
- 爬虫--requests模块高级(代理和cookie操作)
代理和cookie操作 一.基于requests模块的cookie操作 引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests ...
- Scrapy框架--代理和cookie
如何发起post请求? 代理和cookie: cookie:豆瓣网个人登录,获取该用户个人主页这个二级页面的页面数据. 如何发起post请求? 一定要对start_requests方法进行重写. 1. ...
- Scrapy框架之代理和cookie
Cookie 是在 HTTP 协议下,服务器或脚本可以维护客户工作站上信息的一种方式.Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息.无论何时用户 ...
- Jmeter的代理和cookie/session/Token令牌认证
Jmeter的代理服务器 1.启动Jmeter: 2.“测试计划”中添加“线程组”: 3.“工作台”中添加“HTTP代理服务器”: 4.配置代理服务器:Global Settings下面的端口配置:9 ...
- 第三百二十九节,web爬虫讲解2—urllib库爬虫—ip代理—用户代理和ip代理结合应用
第三百二十九节,web爬虫讲解2—urllib库爬虫—ip代理 使用IP代理 ProxyHandler()格式化IP,第一个参数,请求目标可能是http或者https,对应设置build_opener ...
- 八 web爬虫讲解2—urllib库爬虫—ip代理—用户代理和ip代理结合应用
使用IP代理 ProxyHandler()格式化IP,第一个参数,请求目标可能是http或者https,对应设置build_opener()初始化IPinstall_opener()将代理IP设置成全 ...
- Nginx负载均衡中4层代理和7层代理对比
1.4层代理和7层代理什么意思? 这里的层是OSI 7层网络模型,OSI 模型是从上往下的,越底层越接近硬件,越往上越接近软件,这七层模型分别是物理层.数据链路层.网络层.传输层.会话层.表示层.应用 ...
- JDK动态代理和CGLIB的区别
Aspect默认情况下不用实现接口,但对于目标对象,在默认情况下必须实现接口 如果没有实现接口必须引入CGLIB库 我们可以通过Advice中添加一个JoinPoint参数,这个值会由spring自动 ...
- JDK动态代理和CGLib动态代理简单演示
JDK1.3之后,Java提供了动态代理的技术,允许开发者在运行期间创建接口的代理实例. 一.首先我们进行JDK动态代理的演示. 现在我们有一个简单的业务接口Saying,如下: package te ...
随机推荐
- Computer Vision_18_Image Stitching:Automatic Panoramic Image Stitching using Invariant Features——2007
此部分是计算机视觉部分,主要侧重在底层特征提取,视频分析,跟踪,目标检测和识别方面等方面.对于自己不太熟悉的领域比如摄像机标定和立体视觉,仅仅列出上google上引用次数比较多的文献.有一些刚刚出版的 ...
- CentOS 7 根目录分区扩容
查看现有磁盘信息,可以看出根分区有96G [root@localhost ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mappe ...
- 1.使用Vue.js实现品牌案例添加功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 使用Python进行3DES加密-pyDes
pyDes.py源码 ############################################################################# # Documenta ...
- Oracle-锁的查询和处理
1.查出锁定object的session的信息以及被锁定的object名 SELECT L.SESSION_ID SID, S.SERIAL#, L.LOCKED_MODE, L.ORACLE_USE ...
- vue.js v-cloak指令
可以使用 v-cloak 指令设置样式,这些样式会在 Vue 实例编译结束时,从绑定的 HTML 元素上被移除. 当网络较慢,网页还在加载 Vue.js ,而导致 Vue 来不及渲染,这时页面就会显示 ...
- 一步步来用C语言来写python扩展
本文介绍如何用 C 语言来扩展 python.所举的例子是,为 python 添加一个设置字符串到 windows 的剪切板(Clipboard)的功能.我在写... 本文介绍如何用 C 语言来扩展 ...
- [Google Guava] 1.3-常见Object方法
原文链接 译者: 沈义扬 equals 当一个对象中的字段可以为null时,实现Object.equals方法会很痛苦,因为不得不分别对它们进行null检查.使用Objects.equal帮助你执行n ...
- 03_mysql-python模块, linux环境下python2,python3的
---恢复内容开始--- 1.Python2 正常 [root@IP ~]# pip install mysql-python DEPRECATION: Python 2.7 will reach t ...
- show([speed,[easing],[fn]])
show([speed,[easing],[fn]]) 概述 显示隐藏的匹配元素. 这个就是 'show( speed, [callback] )' 无动画的版本.如果选择的元素是可见的,这个方法将不 ...