zoukankan      html  css  js  c++  java
  • requests.get()参数

    查询参数-params

    1.参数类型

      字典,字典中键值对作为查询参数

    2.使用方法

    1、res = requests.get(url,params=params,headers=headers)
    2、特点: 
       * url为基准的url地址,不包含查询参数
       * 该方法会自动对params字典编码,然后和url拼接

    3.示例

    import requests
    
    baseurl = 'http://tieba.baidu.com/f?'
    params = {
      'kw' : '赵丽颖吧',
      'pn' : '50'
    }
    headers = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'}
    # 自动对params进行编码,然后自动和url进行拼接,去发请求
    res = requests.get(baseurl,params=params,headers=headers)
    res.encoding = 'utf-8'
    print(res.text)

    web客户端验证 参数-auth

    1.作用类型

    1、针对于需要web客户端用户名密码认证的网站
    2、auth = ('username','password')

    2.通过用户名账号密码获取笔记名称案例

    import requests
    from lxml import etree
    import os
    
    class NoteSpider(object):
        def __init__(self):
            self.url = 'http://code.com.cn/Code/aid1904/redis/'
            self.headers = {'User-Agent':'Mozilla/5.0'}
            self.auth = ('code','code_2013')
    
        # 获取
        def get_html(self):
            html = requests.get(url=self.url,auth=self.auth,headers=self.headers).text
            return html
    
        # 解析提取数据 + 把笔记压缩包下载完成
        def parse_page(self):
            html = self.get_html()
            xpath_bds = '//a/@href'
            parse_html = etree.HTML(html)
            # r_list : ['../','day01','day02','redis_day01.zip']
            r_list = parse_html.xpath(xpath_bds)
            for r in r_list:
                if r.endswith('zip') or r.endswith('rar'):
                    print(r)
    
    if __name__ == '__main__':
        spider = NoteSpider()
        spider.parse_page()

    思考:爬取具体的笔记文件?

    import requests
    from lxml import etree
    import os
    
    class NoteSpider(object):
        def __init__(self):
            self.url = 'http://code.com.cn/Code/redis/'
            self.headers = {'User-Agent':'Mozilla/5.0'}
            self.auth = ('code','code_2013')
    
        # 获取
        def get_html(self):
            html = requests.get(url=self.url,auth=self.auth,headers=self.headers).text
            return html
    
        # 解析提取数据 + 把笔记压缩包下载完成
        def parse_page(self):
            html = self.get_html()
            xpath_bds = '//a/@href'
            parse_html = etree.HTML(html)
            # r_list : ['../','day01','day02','redis_day01.zip']
            r_list = parse_html.xpath(xpath_bds)
            for r in r_list:
                if r.endswith('zip') or r.endswith('rar'):
                    file_url = self.url + r
                    self.save_files(file_url,r)
    
        def save_files(self,file_url,r):
            html_content = requests.get(file_url,headers=self.headers,auth=self.auth).content
            # 判断保存路径是否存在
            directory = '/home/redis/'
            filename = directory + r
         #适用频率很高
         #if not os.path.exists('路径'):
         #  os.makedirs('路径') 可递归创建
         #  os.mkdir('路径')不能递归创建
    if not os.path.exists(directory): os.makedirs(directory)
         with open(filename,
    'wb') as f: f.write(html_content) print(r,'下载成功') if __name__ == '__main__': spider = NoteSpider() spider.parse_page()

    SSL证书认证参数-verify

    1.适用网站及场景

    1、适用网站: https类型网站但是没有经过 证书认证机构 认证的网站
    2、适用场景: 抛出 SSLError 异常则考虑使用此参数

    2.参数类型

    1、verify=True(默认)   : 检查证书认证
    2、verify=False(常用): 忽略证书认证
    # 示例
    response = requests.get(
        url=url,
        params=params,
        headers=headers,
        verify=False
    )

    代理参数-proxies 

    1.定义

    1、定义: 代替你原来的IP地址去对接网络的IP地址。
    2、作用: 隐藏自身真实IP,避免被封。

    2.普通代理

      获取代理IP网站

    西刺代理、快代理、全网代理、代理精灵、... ... 

      参数类型

    1、语法结构
           proxies = {
               '协议':'协议://IP:端口号'
           }
    2、示例
        proxies = {
            'http':'http://IP:端口号',
            'https':'https://IP:端口号'
        }

      示例代码

        (1)使用免费普通代理IP访问测试网站: http://httpbin.org/get

    import requests
    
    url = 'http://httpbin.org/get'
    headers = {
        'User-Agent':'Mozilla/5.0'
    }
    # 定义代理,在代理IP网站中查找免费代理IP
    proxies = {
        'http':'http://112.85.164.220:9999',
        'https':'https://112.85.164.220:9999'
    }
    html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text
    print(html)

        考: 建立一个自己的代理IP池,随时更新用来抓取网站数据

    1.从代理IP网站上,抓取免费的代理IP
    2.测试抓取的IP,可用的保存在文件中

        (2)一个获取收费开放代理的接口

    # 获取开放代理的接口
    import requests
    
    def test_ip(ip):
        url = 'http://www.baidu.com/'
        proxies = {
            'http':'http://{}'.format(ip),
            'https':'https://{}'.format(ip),
        }
        try:
            res = requests.get(url=url,proxies=proxies,timeout=8)
            if res.status_code == 200:
                   return True
           except Exception as e:
                   return False
    
    # 提取代理IP
    def get_ip_list():
      api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=946562662041898&num=100&protocol=1&method=2&an_an=1&an_ha=1&sep=2'
      html = requests.get(api_url).content.decode('utf-8','ignore')
      ip_port_list = html.split('
    ')
    
      for ip in ip_port_list:
        with open('proxy_ip.txt','a') as f:
            if test_ip(ip):
                f.write(ip + '
    ')
    
    if __name__ == '__main__':
        get_ip_list()
    实现代码

        (3)使用随机收费开放代理IP写爬虫

    import random
    import requests
    
    class BaiduSpider(object):
        def __init__(self):
            self.url = 'http://www.baidu.com/'
            self.headers = {'User-Agent' : 'Mozilla/5.0'}
            self.blag = 1
    
        def get_proxies(self):
            with open('proxy_ip.txt','r') as f:
                #f.readlines:['1.1.1.1:111
    ','2.2.2.2:22
    ']
                result = f.readlines()
            #[:-1] -> 切掉ip,port后的
    
            proxy_ip = random.choice(result)[:-1]
            proxy_ip = {
                'http':'http://{}'.format(proxy_ip),
                'https': 'https://{}'.format(proxy_ip)
            }
            return proxy_ip
    
        def get_html(self):
            proxies = self.get_proxies()
            if self.blag <= 3:
                try:
                    html = requests.get(url=self.url,proxies=proxies,headers=self.headers,timeout=5).text
                    print(html)
                except Exception as e:
                    print('Retry')
                    self.blag += 1
                    self.get_html()
    
    if __name__ == '__main__':
        spider = BaiduSpider()
        spider.get_html()
    实现代码

    3.私密代理

      语法格式

    1、语法结构
    proxies = {
        '协议':'协议://用户名:密码@IP:端口号'
    }
    
    2、示例
    proxies = {
        'http':'http://用户名:密码@IP:端口号',
        'https':'https://用户名:密码@IP:端口号'
    }

      示例代码

    import requests
    url = 'http://httpbin.org/get'
    proxies = {
        'http': 'http://309435365:szayclhp@106.75.71.140:16816',
        'https':'https://309435365:szayclhp@106.75.71.140:16816',
    }
    headers = {
        'User-Agent' : 'Mozilla/5.0',
    }
    
    html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text
    print(html)

    urllib和urllib2关系

    #python2
    urllib :URL地址编码
    urllib2:请求
    #python3 - 把python2中urllib和urllib2合并
    urllib.parse:编码
    urllib.requests: 请求

    控制台抓包

    打开方式几常用选项

    1、打开浏览器,F12打开控制台,找到Network选项卡
    2、控制台常用选项
       1、Network: 抓取网络数据包
            1、ALL: 抓取所有的网络数据包
            2、XHR:抓取异步加载的网络数据包
            3、JS : 抓取所有的JS文件
       2、Sources: 格式化输出并打断点调试JavaScript代码,助于分析爬虫中一些参数
       3、Console: 交互模式,可对JavaScript中的代码进行测试
    3、抓取具体网络数据包后
       1、单击左侧网络数据包地址,进入数据包详情,查看右侧
       2、右侧:
           1、Headers: 整个请求信息
                General、Response Headers、Request Headers、Query String、Form Data
           2、Preview: 对响应内容进行预览
           3、Response:响应内容
  • 相关阅读:
    了解自己,才能踏出成功的第一步
    21世纪非常成功心法[强烈推荐]
    先做人后做事的庸才文化
    职业生涯发展技巧20则
    21世纪非常成功心法[强烈推荐6]
    豁达者的诱惑
    20个问题:平凡的天才人格特质
    21世纪非常成功心法[强烈推荐5]
    测测你的人生会走怎样路线
    21世纪非常成功心法[强烈推荐7]
  • 原文地址:https://www.cnblogs.com/maplethefox/p/11348491.html
Copyright © 2011-2022 走看看