zoukankan      html  css  js  c++  java
  • 爬虫03 /代理、cookie处理、模拟登录、提升爬虫效率

    爬虫03 /代理、cookie处理、模拟登录、提升爬虫效率

    1. 代理

    • 代理概念:代理服务器。

    • 作用:接收请求==》请求转发。

    • 代理和爬虫之间的关联:

      • 可以使用请求转发的机制使得目的服务器接收到的请求对应ip的一个改变。
    • 为什么要使用代理改变请求的ip地址?

      • 爬虫程序在短时间内对指定的服务器发起了一个高频的请求,则请求对应的ip可能会被目的服务器禁止。
    • 代理的一些基础知识:

      • 代理的匿名度:
        • 透明代理:目的服务器知道你使用了代理机制并且也知道你的真实IP
        • 匿名代理:知道使用了代理机制,但是不知道你的真实ip
        • 高匿代理:不知道使用了代理,也不知道你的真实ip
      • 代理的类型:
        • http
        • https
    • 免费代理ip:

      • 快代理
      • 西祠代理
      • www.goubanjia.com
      • 代理精灵
    • get/post方法中使用proxies请求代理的设置

      • proxies={'http':'ip:port'}
    • 需求:测试一下代理是否会生效

      • 准备:
        • 代理ip和端口号
        • 测试的过程
      • 代码示例:
      import requests
      url = 'https://www.baidu.com/s?ie=utf-8&wd=ip'
      headers = {
          'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
      }
      page_text = requests.get(url=url,headers=headers,proxies={'https':'112.195.96.115:32092'}).text
      with open('./ip.html','w',encoding='utf-8') as fp:
          fp.write(page_text)
      
    • 代理池的构建:就是一个列表,列表中存储的是字典。每一个字典存储的键值{'http':'ip:port'}

    • 对西祠代理发起一个高频的请求,使得本机ip被禁止,然后采用代理池解决代理的反爬

      all_ips = []
      url = 'http://t.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=30&time=1&pro=&city=&port=1&format=txt&ss=3&css=&dt=1&specialTxt=3&specialJson=&usertype=2'
      page_text = requests.get(url,headers=headers).text
      tree = etree.HTML(page_text)
      ip_list = tree.xpath('//body//text()')[0].split('
      ')
      for ip in ip_list:
          dic = {
              'https':ip
          }
          all_ips.append(dic)
      
      from lxml import etree
      import random
      url = 'https://www.xicidaili.com/nn/%d'
      ips = []
      for page in range(1,3):
          new_url = format(url%page)
          page_text = requests.get(new_url,headers=headers,proxies=random.choice(all_ips)).text
          tree = etree.HTML(page_text)
          # 在xpath表达式中一定不可以出现tbody标签
          tr_list = tree.xpath('//*[@id="ip_list"]//tr')[1:]
          for tr in tr_list:
              ip = tr.xpath('./td[2]/text()')[0]
              ips.append(ip)
      print(len(ips))
      

    2. cookie处理

    • cookie的处理

      • 手动处理
        • 将cookie作用到headers中即可
      • 自动处理
        • session = requests.Session()
        • session的作用:
          • session可以像requests模块一样调用get和post进行请求发送
          • 在进行请求发送的过程中如果产生了cookie,则cookie会被自动存储到session对象中。
    • 请求头中重要的头信息

      • User-Agent
      • Cookie
      • Referer
    • 需求:https://xueqiu.com/,对雪球网中的新闻数据进行爬取

    • 分析:

      • 新闻数据是通过ajax动态加载出来的
      • 捕获到ajax数据包中的url
    • 代码实现:

      session = requests.Session()
      # 第一次请求发送:为了捕获cookie且存储到session对象中
      first_url = 'https://xueqiu.com/'
      session.get(first_url,headers=headers)
      
      # 第二次请求发送:携带cookie进行的请求发送
      url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20358211&count=15&category=-1'
      json_data = session.get(url=url,headers=headers).json()
      json_data
      

    3. 模拟登录

    • 为什么需要进行模拟登录:

      • 有些数据不经过登录是访问不到
    • 验证码的处理:

      • 基于线上的打码平台来实现
      • 超级鹰的使用流程:
        • 基于用户中心的身份进行注册
        • 用户中心的身份进行登录:
          • 充值
          • 创建一个软件:软件ID-》生成软件ID
          • 下载示例代码:开发文档-》Python-》下载
    • 下载示例代码:

      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()
      
      # 执行代码
      chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '899370')
      im = open('a.jpg', 'rb').read()
      print(chaojiying.PostPic(im, 1902)) 
      
    • 使用打码平台识别古诗文网中的验证码图片

      # 封装一个识别验证码的函数
      def transformCode(imgPath,imgType):
          chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '899370')
          im = open(imgPath, 'rb').read()
          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)
      # 解析到了验证码图片的地址
      code_img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
      img_data = requests.get(code_img_src,headers=headers).content
      with open('./code.jpg','wb') as fp:
          fp.write(img_data)
      transformCode('./code.jpg',1902)
      
    • 模拟登录

      • 对点击登录按钮对应的url进行请求发送
      • 动态变化的请求参数:
        • 一般都会被隐藏在前台页面中
        • 基于抓包工具对请求参数的名称进行全局搜索
    • 古诗文网模拟登录代码示例:

      # 处理cookie
      session = requests.Session()
      
      # 获取且识别验证码
      url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
      page_text = session.get(url,headers=headers).text
      tree = etree.HTML(page_text)
      
      # 解析到了验证码图片的地址
      code_img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
      
      # 解析出模拟登录请求中动态变化的两个请求参数的值
      __VIEWSTATE = tree.xpath('//*[@id="__VIEWSTATE"]/@value')[0]
      __VIEWSTATEGENERATOR = tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')[0]
      
      # 对图片进行请求时捕获cookie
      img_data = session.get(code_img_src,headers=headers).content
      with open('./code.jpg','wb') as fp:
          fp.write(img_data)
      
      # 验证码对应的文本数据
      code_text = transformCode('./code.jpg',1902)
      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': '登录',
      }
      login_page_text = session.post(url=login_url,headers=headers,data=data).text
      with open('./gushiwen.html','w',encoding='utf-8') as fp:
          fp.write(login_page_text)
      

    4. 如何提升爬取数据的效率

    • 线程池

    • 多任务的异步协程

      • asyncio
        • 特殊的函数
        • 协程
        • 任务对象
          • 任务对象绑定
        • 事件循环
    • from multiprocessing.dummy import Pool

    • map(func,alist):

      • 可以让func回调函数处理alist中的每一个列表元素,这个处理的过程是基于异步。
    • 代码示例:

      import requests
      import time
      from multiprocessing.dummy import Pool
      start = time.time()
      pool = Pool(3)
      urls = [
          'http://127.0.0.1:5000/index',
          'http://127.0.0.1:5000/index',
          'http://127.0.0.1:5000/index'
      ]
      # 用作与网络请求(耗时)
      def req(url):
          return requests.get(url).text
      
      page_text_list = pool.map(req,urls)
      print(page_text_list)
      print('总耗时:',time.time()-start)
      

    总结:

    1. 在xpath表达式中一定不可以出现tbody标签
    2. 常见反爬机制:
      • 验证码
      • 动态变化的请求参数
      • cookie
      • 代理
      • UA
      • robots
  • 相关阅读:
    MongoDB导入数据库异常——Failed: cannot decode array into a D
    Unity中实现文字竖排的方法
    MongoDB基础
    基于Vuforia的Unity增强现实应用开发
    Windows设置自动关机
    开源软件的License科普
    87版《红楼梦》与原著回目对应表
    WCF初探-23:WCF中使用Message类(下)
    WCF初探-22:WCF中使用Message类(上)
    WCF初探-21:WCF终结点(endpoint)
  • 原文地址:https://www.cnblogs.com/liubing8/p/11985152.html
Copyright © 2011-2022 走看看