• 爬虫—模拟登陆


    报错HttpConnectinPool:
    原因:

    • 1.短时间内发起了高频的请求导致ip被禁。
    • 2.发送高频的请求且请求成功后没有被及时断开,导致http连接池(http连接对象)中的连接资源被耗尽。
      解决:
    • 1.代理
    • 2.headers中加入Conection:"close",表示请求后连接立即断开。

    代理

    代理:代理服务器,可以接受请求然后将其转发。

    匿名度

    • 透明:知道你使用了代理并且知道你的真实ip
    • 匿名:知道你使用了代理,但是不知道你的真实ip
    • 高匿:啥也不知道
      类型:
    • http,只能转发http请求
    • https,只能转发https请求
      免费代理:
    • www.goubanjia.com
    • 快代理
    • 西祠代理
    • http://http.zhiliandaili.cn/

    使用代理

    import requests
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
        'Connection':"close"
    }
    url = 'https://www.baidu.com/s?ie=UTF-8&wd=ip'
    page_text = requests.get(url,headers=headers,proxies={'https':'1.197.204.153:9999'}).text
    with open('ip.html','w',encoding='utf-8'as fp:
        fp.write(page_text)

    代理可能随时被封

    解决方法:代理池

    #代理池:列表
    import random
    proxy_list = [
        {'https':'121.231.94.44:8888'},
        {'https':'131.231.94.44:8888'},
        {'https':'141.231.94.44:8888'}
    ]
    url = 'https://www.baidu.com/s?wd=ip'
    page_text = requests.get(url,headers=headers,proxies=random.choice(proxy_list)).text
    with open('ip.html','w',encoding='utf-8'as fp:
        fp.write(page_text)

    使用购买代理并爬取代理

    推荐网址:http://http.zhiliandaili.cn/(代理精灵)

    1. 进入网址后注册登陆
    2. 购买后进入API提取
    3. 选择提取类型,提取数量,数据格式(HTML),分隔符(换行),是否去重等等
    4. 选择好后点击生成API链接,复制链接
    # 检测IP是否可用
    def func_ip(proxy_list_http)
            # 随便访问一个网址
            response = requests.get('https://www/sogou.com',headers=headers,proxies={'https':ip})
            # status_code响应状态码
            if response.status_code == '200':

                return True
            elsereturn False
    # 从代理精灵中提取代理ip
    API_url = 'http://t.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=4&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2'
    page_text = requests.get(ip_url,headers=headers).text
    tree = etree.HTML(page_text)
    ip_list = tree.xpath('//body//text()')
    ip_list # 购买的IP

    使用购买的IP爬取免费IP构建代理池

    from lxml import etree

    # 爬取西祠代理
    proxy_list_http = []
    proxy_list_https = []

    def get_ip(url,headers,proxies):
        page_text = requests.get(url,headers=headers,proxies={'https':ip_port}).text
        tree = etree.HTML(page_text)
        # tr_list = tree.xpath('//*[@id="ip_list"]/tbody/tr')
        # tbody不可以出现在xpath表达式中,否则表达式会失效
        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]
            t_type = tr.xpath('./td[6]/text()')[0]
            ips = ip+':'+port

            # 若IP过多,可以存进数据库中,但效率不高,可以直接购买ip
            if t_type == 'HTTP':
                dic = {
                    t_type: ips
                }
                proxy_list_http.append(dic)
            else:
                dic = {
                    t_type:ips
                }
                proxy_list_https.append(dic)


    url = 'https://www.xicidaili.com/nn/%d'
    for page in range(1,20):
        new_url = format(url%page)
        ip_port = random.choice(ip_list)
        if func_ip(ip_port):
            get_ip(new_url,headers,ip_port)
        else:
            ip_list.remove(ip_port)
    print(len(proxy_list_http),len(proxy_list_https))

    Cookie的处理

    Cookie中有请求相关的状态信息,服务器端可以通过Cookie判断请求者的身份信息与状态信息。

    Cookie的处理:

    • 手动处理:将Cookie封装到headers中
    • 自动处理:session对象。可以创建一个session对象,该对象可以像requests一样进行请求发送。不同之处在于如果在使用session进行请求发送的过程中产生了cookie,则cookie会被自动存储在session对象中。

    项目 手动处理Cookie

    对雪球网中的新闻数据进行爬取 urlhttps://xueqiu.com/

    分析:

    • 页面数据是动态加载的(拖动滚轮,页面不断加载,url地址栏不刷新)
    • Request Headers栏中有Cookie信息
    • 可以复制Cookie信息,传入请求头中进行爬取
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
        'Cookie':'aliyungf_tc=AQAAAAl2aA+kKgkAtxdwe3JmsY226Y+n; acw_tc=2760822915681668126047128e605abf3a5518432dc7f074b2c9cb26d0aa94; xq_a_token=75661393f1556aa7f900df4dc91059df49b83145; xq_r_token=29fe5e93ec0b24974bdd382ffb61d026d8350d7d; u=121568166816578; device_id=24700f9f1986800ab4fcc880530dd0ed'
    }
    url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20349203&count=15&category=-1'
    page_text = requests.get(url=url,headers=headers).json()
    page_text

    直接将Cookie添加至请求头,但Cookie有时间限制,每次爬虫可能需要手动处理,使代码不易维护。

    使用session对象自动处理Cookie

    # 创建session对象
    session = requests.Session()

    # 访问网站首页,获取Cookie
    session.get('https://xueqiu.com',headers=headers)

    # 利用session对象爬取页面
    url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20349203&count=15&category=-1'
    page_text = session.get(url=url,headers=headers).json()
    page_text

    模拟登陆

    验证码的识别:要基于打码平台识别识别验证码。
    相关平台:

    • 打码兔

    • 云打码

    • 超级鹰:http://www.chaojiying.com/about.html

    本教程使用超级鹰平台:

    • 注册:(用户中心身份)
    • 登陆:
      • 软件ID-->生成一个软件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()

    模拟登陆古诗文网

    urlhttps://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx

    # 识别古诗文网登陆页面中的验证码
    def tranformImgData(imgPath,t_type):
        # 超级鹰用户名, 超级鹰用户名的密码,软件ID
        chaojiying = Chaojiying_Client('chongxiao''chongxiao''907070')
        # 本地图片文件路径
        im = open(imgPath, 'rb').read()
        # chaojiying返回一个字典,pic_str键的值是图形中的验证码
        return chaojiying.PostPic(im, t_type)['pic_str']

    url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/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(img_src,headers=headers).content
    with open('./code.jpg','wb'as fp:
        fp.write(img_data)

    # 1004 验证码类型
    tranformImgData('./code.jpg',1004

    分析:

    • 将分析成功的字符串验证码发送给古诗文网
    • 在浏览器直接登录,用抓包工具,找到哪一个数据包发送的登录请求,一般为POST请求,且Form Data中有请求的用户名与密码数据。
    • 找到发送登录请求的数据包为login.aspx?from…;从General中找到Request URL,并且发现该数据包请求头中有Cookie。
    • 退出账号再次登录,发现From Data的前两个参数与第一次不一样,即为动态变化的。
    • 猜测动态参数是由隐藏的input标签携带,在登录页面,找到对应的页面数据包,进行全局全局搜索,搜索变化参数的键值,结果与猜测一样。
    • 选择隐藏的input标签,右键copy Xpath表达式。
    #模拟登陆
    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]

    # 此处用requests对象请求,却发现仍无法请求成功,经分析发现,登录的Cookie是由获取图片的请求携带的。      
    img_data = s.get(img_src,headers=headers).content
    with open('./code.jpg','wb'as fp:
        fp.write(img_data)

    #动态获取变化的请求参数
    __VIEWSTATE = tree.xpath('//*[@id="__VIEWSTATE"]/@value')[0]
    __VIEWSTATEGENERATOR = tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')[0]

    code_text = tranformImgData('./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''www.chongxiao@qq.com',
        'pwd''chongxiao',
        'code': code_text,
        'denglu''登录',
    }
    page_text = s.post(url=login_url,headers=headers,data=data).text
    with open('login.html','w',encoding='utf-8'as fp:
        fp.write(page_text)

    动态变化的请求参数:通常情况下动态变化的请求参数都会被隐藏在前台页面源码中。

    携带Cookie的响应:服务器发送Cookie不一定是请求登录页面发送的,也可能是请求某个动态数据或图片发送的,若用session对象处理Cookie,则最好每一个请求都用session对象发送。

  • 相关阅读:
    RFM模型
    mysql日期函数(时间函数)
    数据库探索
    anaconhda安装步骤
    mysql安装和环境配置
    mysql时间条件查询
    mysql自连接
    mysql查询注意事项(查询优化)
    mysql常见的保留字和反引号使用
    多表联合查询注意事项(索引)
  • 原文地址:https://www.cnblogs.com/wby-110/p/13467805.html
Copyright © 2020-2023  润新知