代理和cookie操作

一.基于requests模块的cookie操作

引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests模块常规操作时,往往达不到我们想要的目的,例如:

cookie会话跟踪技术,服务端产生发给客户端保存,再次访问服务器,浏览器就携带这个cookie,让服务器识别客户端浏览器

爬取张三用户的豆瓣网的个人主页页面数据--没有测试成功

- cookie:基于用户的用户数据
- 需求:爬取张三用户的豆瓣网的个人主页页面数据
- cookie作用:服务器使用cookie来记录客户端的状态信息
实现流程:
1.执行登录操作(获取cookie)
2.发起个人主页请求时,需要将cookie携带到该请求中
注意:session对象

  1. import requests
  2.  
  3. session = requests.session()
  4. # 1.发起登录请求:将cookie获取,切换存储到session对象中
  5. login_url = 'https://accounts.douban.com/login'
  6. # post 请求 ---data参数
  7. data = {
  8. 'source':'movie',
  9. 'redir':'https://movie.douban.com/',
  10. 'form_email':'',
  11. 'form_password':'',
  12. 'login':'登录',
  13. }
  14.  
  15. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  16. # 使用session发起请求
  17. login_response = session.post(url=login_url,data=data,headers=headers)
  18.  
  19. # 2.发起个人主页请求(session(cookie)),获取响应页面数据
  20. url = 'https://www.douban.com/people/188197188/'
  21. response = session.get(url=url,headers=headers)
  22. page_text = response.text
  23. with open('./douban110.html','w',encoding='utf-8')as f:
  24. f.write(page_text)

代理操作

- 1.代理:第三方代理本体执行相关的事务。生活:代购
- 2.为什么要使用代理
  - 反爬操作,非正常访问的ip禁止
  - 反反爬手段--设置爬虫的代理ip
- 3.分类:
  - 正向代理:代替客户端获取数据--爬虫客户端程序-正向代理
  - 反向代理:代理服务器端提供数据
- 4.免费代理ip的网站提供商
  - www.goubanjia.com 推荐
  - 快代理
  - 西祠代理
- 5.代码

http://www.goubanjia.com/

---------------------------------------------------------------------------------------------

  1. import requests
  2.  
  3. url = 'http://www.baidu.com/s?ie=utf-8&wd=ip'
  4. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  5. # 将代理ip封装到字典中
  6. proxy = {
  7. 'http':'112.25.6.26:80'
  8. }
  9.  
  10. # 更换网络ip,发起请求之前
  11. response = requests.get( url=url,proxies=proxy,headers=headers)
  12. with open('./daili.html','w',encoding='utf-8')as f:
  13. f.write(response.text)
  14.  
  15. 执行后结果:
  16.  

验证处理--打码平台

登陆的次数过多就会出现验证码

验证码处理:

  1. - 1.手动识别验证码
  2. - 2.云打码平台自动识别验证码
 

云打码平台处理验证码的实现流程:

  1. - 1.对携带验证码的页面数据进行抓取
  2. - 2.可以将页面数据中验证码进行解析,验证码图片下载到本地
  3. - 3.可以将验证码图片提交给三方平台进行识别,返回验证码图片上的数据值
  4. - 云打码平台:
  5. - 1.在官网中进行注册(普通用户和开发者用户)
  6. - 2.登录开发者用户:
  7. - 1.实例代码的下载(开发文档-》调用实例及最新的DLL-》PythonHTTP实例下载)
  8. - 2.创建一个软件:我的软件-》添加新的软件
  9. -3.使用示例代码中的源码文件中的代码进行修改,让其识别验证码图片中的数据值

如何获取验证码图片上的数据值

1.到官网进行注册(普通用户和开发者用户)

- 2.登录开发者用户:

下载后解压放在jupyter notebook相应目录下

2.创建一个软件:点击我的软件---》添加新的 软件

3.使用示例代码中的源码文件中的代码进行修改,让其识别验证码图片中的数据值

识别成功:

进行登录操作:

抓包:

  1. import requests
  2. from lxml import etree
  3. import json,time,re
  4. url = 'https://www.douban.com/accounts/login?source=movie'
  5.  
  6. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  7.  
  8. page_text = requests.get(url=url,headers=headers).text
  9. # 2.可以将页面数据中验证码进行解析,验证码图片下载到本地
  10. tree = etree.HTML(page_text)
  11. # 验证码图片xpath 的值: //*[@id="captcha_image"]
  12. codeImg_url = tree.xpath('//*[@id="captcha_image"]/@src')[0]
  13. # 获取了验证码图片的二进制数据值
  14. code_img = requests.get(url=codeImg_url,headers=headers).content
  15.  
  16. # 获取captcha-id
  17.  
  18. # 正则解析
  19. # 使用re.S参数以后,正则表达式会将这个字符串作为一个整体,将“\n”当做一个普通的字符加入到这个字符串中,在整体中进行匹配。
  20.  
  21. # <img id="captcha_image" src="https://www.douban.com/misc/captcha?id=O1pMk4XJ7wuKuLz8DYhVZpw3:en&amp;size=s" alt="captcha" class="captcha_image">
  22. c_id = re.findall('<img id="captcha_image".*?id=(.*?)&amp.*?>',page_text,re.S)[0]
  23.  
  24. with open('./code.png','wb')as f:
  25. f.write(code_img)
  26.  
  27. # 调用验证码函数,获取识别结果
  28. codeText = getCode('./code.png')
  29. print(codeText)
  30.  
  31. # 进行登录操作
  32.  
  33. post = 'https://accounts.douban.com/login'
  34.  
  35. data = {
  36. 'source':'movie',
  37. 'redir':'https://movie.douban.com/',
  38. 'form_email':'836342406@qq.com',
  39. 'form_password':'xl836342406,.',
  40. 'captcha-solution':codeText,
  41. 'captcha-id':c_id,
  42. 'login':'登录',
  43. }
  44.  
  45. print(c_id)
  46. login_text = requests.post(url=post,data=data,headers=headers).text
  47. with open('./login.html','w',encoding='utf-8')as f:
  48. f.write(login_text)

---

  1. # 该函数调用了打码平台的相关接口对指定的验证码识别,返回识别结果
  2.  
  3. def getCode(codeImg):
  4. # 普通云打码用户名
  5. username = 'foremost'
  6.  
  7. # 密码
  8. password = 'ydm(qq)'
  9.  
  10. # 软件ID,开发者分成必要参数。登录开发者后台【我的软件】获得!
  11. appid = 6322
  12.  
  13. # 软件密钥,开发者分成必要参数。登录开发者后台【我的软件】获得!
  14. appkey = '4b936b7eb8060d3b7667b8098dd85233'
  15.  
  16. # 验证码图片文件
  17. filename = codeImg
  18.  
  19. # 验证码类型,# 例:1004表示4位字母数字,不同类型收费不同。请准确填写,否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
  20. codetype = 3000
  21.  
  22. # 超时时间,秒
  23. timeout = 20
  24.  
  25. # 检查
  26. if (username == 'username'):
  27. print('请设置好相关参数再测试')
  28. else:
  29. # 初始化
  30. yundama = YDMHttp(username, password, appid, appkey)
  31.  
  32. # 登陆云打码
  33. uid = yundama.login();
  34. print('uid: %s' % uid)
  35.  
  36. # 查询余额
  37. balance = yundama.balance();
  38. print('balance: %s' % balance)
  39.  
  40. # 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
  41. cid, result = yundama.decode(filename, codetype, timeout);
  42. print('cid: %s, result: %s' % (cid, result))
  43.  
  44. # ---自己加
  45. return result

----

  1. class YDMHttp:
  2.  
  3. apiurl = 'http://api.yundama.com/api.php'
  4. username = ''
  5. password = ''
  6. appid = ''
  7. appkey = ''
  8.  
  9. def __init__(self, username, password, appid, appkey):
  10. self.username = username
  11. self.password = password
  12. self.appid = str(appid)
  13. self.appkey = appkey
  14.  
  15. def request(self, fields, files=[]):
  16. response = self.post_url(self.apiurl, fields, files)
  17. response = json.loads(response)
  18. return response
  19.  
  20. def balance(self):
  21. data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
  22. response = self.request(data)
  23. if (response):
  24. if (response['ret'] and response['ret'] < 0):
  25. return response['ret']
  26. else:
  27. return response['balance']
  28. else:
  29. return -9001
  30.  
  31. def login(self):
  32. data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
  33. response = self.request(data)
  34. if (response):
  35. if (response['ret'] and response['ret'] < 0):
  36. return response['ret']
  37. else:
  38. return response['uid']
  39. else:
  40. return -9001
  41.  
  42. def upload(self, filename, codetype, timeout):
  43. data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
  44. file = {'file': filename}
  45. response = self.request(data, file)
  46. if (response):
  47. if (response['ret'] and response['ret'] < 0):
  48. return response['ret']
  49. else:
  50. return response['cid']
  51. else:
  52. return -9001
  53.  
  54. def result(self, cid):
  55. data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid)}
  56. response = self.request(data)
  57. return response and response['text'] or ''
  58.  
  59. def decode(self, filename, codetype, timeout):
  60. cid = self.upload(filename, codetype, timeout)
  61. if (cid > 0):
  62. for i in range(0, timeout):
  63. result = self.result(cid)
  64. if (result != ''):
  65. return cid, result
  66. else:
  67. time.sleep(1)
  68. return -3003, ''
  69. else:
  70. return cid, ''
  71.  
  72. def report(self, cid):
  73. data = {'method': 'report', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'cid': str(cid), 'flag': ''}
  74. response = self.request(data)
  75. if (response):
  76. return response['ret']
  77. else:
  78. return -9001
  79.  
  80. def post_url(self, url, fields, files=[]):
  81. for key in files:
  82. files[key] = open(files[key], 'rb');
  83. res = requests.post(url, files=files, data=fields)
  84. return res.text

----

结果:

爬虫--requests模块高级(代理和cookie操作)的更多相关文章

  1. 爬虫 requests模块高级用法

    一 介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内 ...

  2. requests模块 高级应用

    目录 requests模块 高级应用 HttpConnectinPool 问题解决 IP代理 简单使用代理 代理池 cookie的处理 页面中验证码识别 使用 multiprocessing.dumm ...

  3. Scrapy框架--代理和cookie

    如何发起post请求? 代理和cookie: cookie:豆瓣网个人登录,获取该用户个人主页这个二级页面的页面数据. 如何发起post请求? 一定要对start_requests方法进行重写. 1. ...

  4. requests模块高级

    requests模块高级 cookie cookie: 基于用户的用户数据 -需求:爬取用户的豆瓣网的个人页面数据 cookie作用:服务器端使用cookie来记录客户端的状态信息 实现流程: 1.执 ...

  5. 爬虫 requests模块的其他用法 抽屉网线程池回调爬取+保存实例,gihub登陆实例

    requests模块的其他用法 #通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下 Host Referer #大型网站通常都会根据该参数判断请求的来源 ...

  6. 爬虫 requests 模块

    requests 模块 介绍 使用requests可以模拟浏览器的请求, 比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) ps: requests库发 ...

  7. 爬虫----requests模块

    一.介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内 ...

  8. 爬虫--requests模块学习

    requests模块 - 基于如下5点展开requests模块的学习 什么是requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能 ...

  9. Python网络爬虫-requests模块(II)

    有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests模块常规操作时,往往达不到我们想要的目的,例如: #!/usr/bin/env ...

随机推荐

  1. tcpdump命令(转载)

    https://www.cnblogs.com/ggjucheng/archive/2012/01/14/2322659.html 简介 用简单的话来定义tcpdump,就是:dump the tra ...

  2. AMQP & JMS对比(转载)

    AMQP & JMS对比 原文地址:https://blog.csdn.net/hpttlook/article/details/23391967 初次接触消息队列时,在网上搜索,总是会提到如 ...

  3. http和https的区别联系

    超文本传输协议HTTP协议被用于在Web浏览器和网站服务器之间传递信息,HTTP协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和网站服务器之间的传输报文,就可以直接读懂 ...

  4. sqlserver 数据简单查询

    use StudentManageDB go select StudentName as 姓名,Gender as 性别,出生日期=birthday from Students where Gende ...

  5. CLion使用OpenCV(Ubuntu 18.04)

    项目结构: 设置CMainLists.txt文件中的内容: cmake_minimum_required(VERSION 3.13) project(cv_test) ) find_package(O ...

  6. POJ3159 Candies

    #include <iostream> #include <queue> #include <cstring> #define maxn 30005 #define ...

  7. DB通用类:Access通用类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  8. nodejs使用案例-mysql操作

    1.package.json: { "scripts": { "start": "node app.js" }, "devDepe ...

  9. 线程守护进程与GIL

    为何要用多线程 多线程指的是,在一个进程中开启多个线程,简单的讲:如果多个任务共用一块地址空间,那么必须在一个进程内开启多个线程.详细的讲分为4点: 1. 多线程共享一个进程的地址空间 2. 线程比进 ...

  10. 流(Stream)与文件流(FileStream)

    //通过流的方式添加 StreamWriter writer = new StreamWriter(@"C:\A\ca.txt", true, Encoding.Default); ...