爬虫之requests进阶

requests模块高级

代理(反爬机制)

短时间向一个服务器发起高频请求,会被认定为异常请求,将当前IP列入黑名单

  • 概念:在爬虫中指的就是代理服务器
  • 代理服务器的作用:
    • 拦截请求和响应,进行转发
  • 代理和爬虫之间的关联?
    • 如果pc端IP被禁掉后,我们就可以使用代理机制更换请求的IP
  • 如何获取相关的代理服务器
    • 快代理:https://www.kuaidaili.com/
    • 西刺代理:https://www.xicidaili.com/
    • 代理精灵:http://http.zhiliandaili.com/(推荐使用,便宜)
    • 购半价:http://www.goubanjia.com/
  • 匿名度
    • 透明:知道你使用代理,也知道你的真实IP
    • 匿名:对方服务器知道你使用了代理机制,但是不会到你的真实IP
    • 高匿名:对方服务器不知道你使用了代理机制,更不知道你的真实IP
  • 类型
    • http:只可以拦截转发http协议的请求
    • https:证书秘钥加密,只可以转发拦截https的请求

基本使用

  • 基于搜狗ip搜索,搜索到的页面中会显示该请求对应的ip地址
    • https://www.sogou.com/web?query=ip
  • 语法结构
    • get/post(proxies={'http/https':'ip:prot'})
import requests
from lxml import etree
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
url = "https://www.sogou.com/web?query=ip"
# 代理机制对应的就是get或者post方法中一个叫做proxies的参数
page_text = requests.get(url=url,headers=headers,proxies={"https":'221.1.200.242:38652'}).text
tree = etree.HTML(page_text)
# 在Xpath表达式中不能出现tbody标签
ip = tree.xpath('//*[@id="ipsearchresult"]/strong/text()')[0]
print(ip)

构建代理池

爬取某一网站请求过多会被封IP,所以要使用代理池

  • 将西刺代理中的免费代理IP进行爬取
    • https://www.xicidaili.com/nn/
import requests
import random
from lxml import etree
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}

all_ips = []
api_url = "购买代理精灵付费ip生成的html的地址"
api_text = requests.get(url=api_url,headers=headers).text
api_tree = etree.HTML(api_text)
datas = api_tree.path('//body//text()')     # 取出所有文本
for data in datas:
    dic = {
        'https':data
    }
    all_ips.append(dic)     # 以字典的形式[{},{}...]
   

url = "https://www.xicidaili.com/nn/%d"  # 定义一个通用的url模板
ip_datas = []  # 解析到的所有数据
for page_num in range(1,50):    # 页码越多,代理池ip就越多,ip有效时长多一点
    new_url = format(url%page_num)
    page_text=requests.get(url=new_url,headers=headers,proxies=random.choice(all_ips)).text
    tree =etree.HTML(page_text)
    tr_lst = tree.xpath('//*[@id="ip_list"]//tr')[1:]
    for tr in tr_lst:# 局部数据解析
        ip = tr.xpath('./td[2]/text()')[0]
        prot = tr.xpath('./td[3]/text()')[0]
        dic_ = {
            "https":ip + ":" + prot
        }
        ip_datas.append(dic_)
print(len(datas))   # 爬取到的ip

模拟登录

  • 为什么要实现模拟登录?
    • 相关页面是必须经过登陆之后才可见的

验证码处理

  • 验证码的处理

    • 使用相关的打码平台进行验证码的动态识别
    • 打码平台
      • 超级鹰(推荐,可以识别12306验证)
        • http://www.chaojiying.com/
      • 云打码
    • 超级鹰使用流程

      • 注册【用户中心】身份的帐号

      • 登录

        • 创建一个软件

          用户中心→软件ID→添加软件

        • 下载示例代码

#!/usr/bin/env python
# coding:utf-8

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 transform_code(imgPath,imgType):
    chaojiying = Chaojiying_Client('超级鹰用户名', '超级鹰用户名的密码', '用户中心>>软件ID')
    im = open(imgPath, 'rb').read()
    return chaojiying.PostPic(im, imgType)['pic_str']

cookie处理

  • 手动处理
    • 将请求携带的cookie封装到headers中
  • 自动处理
    • session对象,该对象和requests都可以进行get和post请求的发送; 使用session对象发送请求过程中,产生的cookie会被自动存储到session对象中; cookie存储到session对象中后,再次使用session进行请求发送,则该次请求就是携带着cookie发送的请求。
    • session处理cookie的时候,session对象最少发几次请求?
      • 两次。第一次是为了获取和存储cookie;第二次才是携带cookie进行的请求发送。
    • session = requests.Session()

需求:爬取雪球网中的新闻标题和内容

  • 手动处理cookie
    • 有局限性,不能保证cookie的有效时长
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
    # 手动处理
    # 'Cookie':'aliyungf_tc=AQAAANpdTCedNgQA0EVI33fxpCso1BVS; acw_tc=2760823015846080972884781e8f986f089c7939870e775a86ffb898ca91d4; xq_a_token=a664afb60c7036c7947578ac1a5860c4cfb6b3b5; xqat=a664afb60c7036c7947578ac1a5860c4cfb6b3b5; xq_r_token=01d9e7361ed17caf0fa5eff6465d1c90dbde9ae2; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTU4NTM2MjYwNywiY3RtIjoxNTg0NjA4MDcwNzY4LCJjaWQiOiJkOWQwbjRBWnVwIn0.gwlwGxWjdyWuNGniaTqxswJjO6nKJY9PCJ0aCif9vuHvsUXEI7iW7_wIvBhDC1WTk86J8ayJ_bZd-KxySHAd1Z8kyM6TV80l931tmestgj1I6uP66WsaUZ3PYDBC4KO1chuEqmw_nCa1UhSjWrc-4moKmMbbll6RyvPSocfRxrvrQY-DX_1uBcs_BsRcAakyOEcWxO01tgfQQoVEbd9apgudAXTQc3haJPTLZpqYH62CYYIJZwHGsbI0emF1k1Wmp_539girZEmPnE7NgK6N1I8tqTdh_XaDTFfFK07G177w84nVuJfsB8hPca6rzYDUGPAMAWqQJcPEUSDzDKhkdA; u=301584608097293; Hm_lvt_1db88642e346389874251b5a1eded6e3=1584608100; device_id=24700f9f1986800ab4fcc880530dd0ed; cookiesu=901584608234987; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1584608235'
}

url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?'
params = {
    'since_id': '-1',
    'max_id': '20369159',
    'count': '15',
    'category': '-1',
}
page_json = requests.get(url=url,headers=headers,params=params).json()
print(page_json)
  • 自动处理
    • 推荐使用,每次都可以获取新的cookie
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
# 实例化一个session对象
session = requests.Session()
# 试图将cookie获取且存储到session对象中,url得试着来
session.get('https://xueqiu.com/',headers=headers)
# url地址
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?'
# 发请求索携带的参数
params = {
    'since_id': '-1',
    'max_id': '20369159',
    'count': '15',
    'category': '-1',
}
# 携带cookie的发送求情
page_json = session.get(url=url,headers=headers,params=params).json()
print(page_json)

案例:古诗文网模拟登陆

  • url:https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx
  • 分析
    • 通过抓包工具定位到点击登录按钮对应的数据包(包含用户名、密码、验证码)
    • 从数据包中取出请求的url,请求方式,请求参数
import requests
from lxml import etree

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}

# 网站涉及到cookie,直接实例化session对象,所有请求都用session发送
session = requests.Session()
# 验证码识别
first_url = "https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx"
page_text = session.get(first_url,headers=headers).text
tree = etree.HTML(page_text)
code_img_src = "https://so.gushiwen.org/" + tree.xpath('//*[@id="imgCode"]/@src')[0]

# 对验证码图片的地址进行发请求,产生了cookie
code_img_data = session.get(code_img_src,headers=headers).content
with open('./code.jpg','wb') as f:
    f.write(code_img_data)

# 基于超级鹰识别验证码,可以将超级鹰的包导入,因为我用的是jupyter,上面运行过超级鹰的包和我写的函数,所以直接拿来用了,使用pycharm的话就导入一下
# from chaojiying import transform_code
code_img_text = transform_code('./code.jpg',1902)
# 识别验证码也不是百分百成功的,所以查看一下
print(code_img_text)
url = 'https://so.gushiwen.org/user/login.aspx'

# 动态参数
data = {
    '__VIEWSTATE': 'ldci9GbqVEF2rdreR42gQu3m7xrlS5IibH9mPop+Qc1ONCWpo9EQCzSxUHhInXI26x0x19nb1l6gw26SC8qi4q/XnaPcK67OGf/fGDOfhuewFPnrLznJctqf/no=',
    '__VIEWSTATEGENERATOR': 'C93BE1AE',
    'from': 'http://so.gushiwen.org/user/collect.aspx',
    'email': '网站帐号',
    'pwd': '网站密码',
    'code': code_img_text,
    'denglu': '登录',
}
page_text = session.post(url=url,headers=headers,data=data).text
with open('./古诗文.html','w',encoding='utf-8') as f:
    # 将登陆后的页面持久化存储
    f.write(page_text)

遇到了动态变化的请求参数该如何处理?

  • 通常情况下,动态变化的请求参数的值都会被隐藏在前台页面中
  • 基于抓包工具进行全局搜索(基于js逆向获取相关的参数值)

猜你喜欢

转载自www.cnblogs.com/Golanguage/p/12526358.html