requests模块高级操作

  • 爬虫中cookie的处理方式有两种
    • 手动处理
      • 将抓包工具中的cookie写入到headers中即可
    • 自动处理
      • session对象。该对象可以像requests一样进行get和post请求的发送。唯一的不同之处在于,如果使用session进行请求发送的,如果在请求中产生了cookie,则cookie会被自动保存到该session对象中。
      • 在爬虫使用session对象,该对象至少要被爬虫程序调用两次。
sess = requests.Session() #返回一个session对象
#第一次调用session一定是为了捕获cookie
main_url = 'https://xueqiu.com/'
sess.get(main_url,headers=headers) #目的:尝试捕获cookie,cookie就会被存储到session

url = 'https://xueqiu.com/statuses/hot/listV2.json?since_id=-1&max_id=65993&size=15'
#已经表示携带cookie发起了请求
json_data = sess.get(url=url,headers=headers).json()
json_data
  • 代理机制
    • 什么是代理
      • 代理服务器
    • 代理的作用
      • 转发请求&响应。
    • 代理和爬虫之间的关联
      • 如果短时间内,向服务器端发起了高频的网络请求,服务器端会检测到这样的异常现象,可能就会将客户端的ip禁掉,表示当前客户端就无法再次访问该服务器端。
  • 代理的基本概念
    • 代理的匿名度
      • 透明:目的服务器可以知道你使用了代理,也知道你的真实ip
      • 匿名:不知道你使用了代理,但是知道你的真是ip
      • 高匿:不知道使用了代理,也不知道真是ip
    • 代理的类型:
      • http:该代理只可以转发http协议的请求
      • https:只可以转发https协议的请求
  • 如何获取代理?
from lxml import etree
#没有使用代理获取的本机ip
url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=ip'
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
#在xpath表达式中不可以出现tbody标签,否则会解析出错
ip_data = tree.xpath('//*[@id="1"]/div[1]/div[1]/div[2]/table//tr/td/span/text()')
ip_data

['本机IP:\xa0106.115.33.66']

#使用代理
url = 'https://www.sogou.com/web?query=ip&_asf=www.sogou.com&_ast=&w=01019900&p=40040100&ie=utf8&from=index-nologin&s_from=index&sut=731&sst0=1592443705688&lkt=2%2C1592443704957%2C1592443705064&sugsuv=00A3ECEE7B7013775D31BAFA55B79106&sugtime=1592443705688'
#proxies参数:请求设置代理
page_text = requests.get(url=url,headers=headers,proxies={'https':'27.40.92.66:36542'}).text
# tree = etree.HTML(page_text)
# #在xpath表达式中不可以出现tbody标签,否则会解析出错
# ip_data = tree.xpath('//*[@id="1"]/div[1]/div[1]/div[2]/table//tr/td/span/text()')
# ip_data
with open('./ip.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

代理池构建

#尝试发起高频请求,让对方服务器将本机ip禁掉
url = 'https://www.xicidaili.com/nn/%d'
ips = []
for page in range(1,30):
    new_url = format(url%page)
    page_text = requests.get(new_url,headers=headers).text
    tree = etree.HTML(page_text)
    #不要第一个tr
    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))
#发现本机ip被禁掉
proxy_list = [] #代理池
proxy_url = 'http://t.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=20&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2'
page_text = requests.get(url=proxy_url,headers=headers).text
tree = etree.HTML(page_text)
ips_list = tree.xpath('//body//text()')
for ip in ips_list:
    dic = {'https':ip}
    proxy_list.append(dic)
    
url = 'https://www.xicidaili.com/nn/%d'
ips = []
for page in range(1,5):
    new_url = format(url%page)
    page_text = requests.get(new_url,headers=headers,proxies=random.choice(proxy_list)).text
    tree = etree.HTML(page_text)
    #不要第一个tr
    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))
  • 验证码的识别
    • 将古诗文网中的验证码进行识别
  • 需要基于一些线上的打码平台进行验证码识别
    • 需要将页面中的验证码图片进行下载,然后将其提交给平台进行识别
  • 常用的打码平台:
    • 超级鹰(讲解):https://www.chaojiying.com/
      • 注册:注意用户中心的账号
      • 登录:登录用户中心身份的账号
      • 题分充值
      • 创建一个软件ID:899370
      • 下载平台提供的示例代码
    • 云打码
    • 打码兔
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]
img_data = requests.get(url=img_src,headers=headers).content
with open('./code.jpg','wb') as fp:
    fp.write(img_data)
#!/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_codeImg(imgPath,imgType):
    chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '899370')	#用户中心>>软件ID 生成一个替换 96001
    im = open(imgPath, 'rb').read()			#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    return chaojiying.PostPic(im, imgType)['pic_str']		#1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
transform_codeImg('./code.jpg',1004)
'e9gj'
  • 模拟登录古诗文网
    • 动态变化的请求参数,如何处理?
      • 两种处理方式
        • 有可能会隐藏在前台页面源码中
        • 有可能是存在于某一个js函数代码
          • 基于抓包工具做全局搜索
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)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = session.get(url=img_src,headers=headers).content
__VIEWSTATE = tree.xpath('//*[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')[0]
with open('./code.jpg','wb') as fp:
    fp.write(img_data)

code_text = transform_codeImg('./code.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': '15027900535',
    'pwd': 'bobo@328410948',
    'code': code_text,
    'denglu': '登录',
}
page_text = session.post(url=login_url,headers=headers,data=data).text
with open('./login.html','w',encoding='utf-8') as fp:
    fp.write(page_text)

猜你喜欢

转载自www.cnblogs.com/freedom0923/p/13167635.html
今日推荐