• 爬虫3:requests库


     
    一个简单易用的http库,多用于第一步,爬取网站源码
     
    简单例子
    import requests
     
    response = requests.get('https://www.baidu.com/')
    print(type(response))
    print(response.status_code)
    print(type(response.text))  //字符串类型
    print(response.text)
    print(response.cookies)
     
     

    一. requests的几种请求方式

    import requests
    requests.post('http://httpbin.org/post')
    requests.put('http://httpbin.org/put')
    requests.delete('http://httpbin.org/delete')
    requests.head('http://httpbin.org/get')
    requests.options('http://httpbin.org/get')
     
     

    1. 基本GET请求

    import requests
     
    response = requests.get('http://httpbin.org/get')
    print(response.text)
     

    2. 带参数的GET请求

    import requests
    print(response.text)
     
    使用params参数简化操作
    import requests
     
    data = {
        'name': 'germey',
        'age': 22
    }
    response = requests.get("http://httpbin.org/get", params=data)
    print(response.text)
     

    3. 解析json

    import requests
    import json
     
    response = requests.get("http://httpbin.org/get")
    print(type(response.text))
    print(response.json())
    print(json.loads(response.text))
    print(type(response.json())
     
     

    4. 获取2进制数据

    import requests
     
    response = requests.get("https://github.com/favicon.ico")
    print(type(response.text), type(response.content))
    print(response.text) //和下面的做比较
    print(response.content) //获取2进制内容
     
    保存2进制文件
    import requests
     
    response = requests.get("https://github.com/favicon.ico")
    with open('favicon.ico', 'wb') as f:
        f.write(response.content)
        f.close()
     
     

    5. 添加headers

     
    import requests
     
    response = requests.get("https://www.zhihu.com/explore")
    print(response.text)
    上面代码不加header内容会报错500,修改如下即可
     
    import requests
     
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    response = requests.get("https://www.zhihu.com/explore", headers=headers)
    print(response.text)
     
     
     
     

    二. 基本POST请求

    import requests
     
    data = {'name': 'germey', 'age': '22'}
    response = requests.post("http://httpbin.org/post", data=data)
    print(response.text)
     
    加一个header
    import requests
     
    data = {'name': 'germey', 'age': '22'}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    response = requests.post("http://httpbin.org/post", data=data, headers=headers)
    print(response.json())
     
     
     
     

    三. 响应

     

    1. response属性

     
    import requests
     
    response = requests.get('http://www.jianshu.com')
    print(type(response.status_code), response.status_code)
    print(type(response.headers), response.headers)
    print(type(response.cookies), response.cookies)
    print(type(response.url), response.url)
    print(type(response.history), response.history)
     
     

    2. 状态码判断

     
    1)使用状态码相对应文本
    import requests
     
    response = requests.get('http://www.jianshu.com/hello.html')
    exit() if not response.status_code == requests.codes.not_found else print('404 Not Found')
     
    2)使用状态码数字
    import requests
     
    response = requests.get('http://www.jianshu.com')
    exit() if not response.status_code == 200 else print('Request Successfully')
     
    3)状态码对应文本
    100: ('continue',),
    101: ('switching_protocols',),
    102: ('processing',),
    103: ('checkpoint',),
    122: ('uri_too_long', 'request_uri_too_long'),
    200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
    201: ('created',),
    202: ('accepted',),
    203: ('non_authoritative_info', 'non_authoritative_information'),
    204: ('no_content',),
    205: ('reset_content', 'reset'),
    206: ('partial_content', 'partial'),
    207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
    208: ('already_reported',),
    226: ('im_used',),
     
    # Redirection.
    300: ('multiple_choices',),
    301: ('moved_permanently', 'moved', '\o-'),
    302: ('found',),
    303: ('see_other', 'other'),
    304: ('not_modified',),
    305: ('use_proxy',),
    306: ('switch_proxy',),
    307: ('temporary_redirect', 'temporary_moved', 'temporary'),
    308: ('permanent_redirect',
          'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
     
    # Client Error.
    400: ('bad_request', 'bad'),
    401: ('unauthorized',),
    402: ('payment_required', 'payment'),
    403: ('forbidden',),
    404: ('not_found', '-o-'),
    405: ('method_not_allowed', 'not_allowed'),
    406: ('not_acceptable',),
    407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
    408: ('request_timeout', 'timeout'),
    409: ('conflict',),
    410: ('gone',),
    411: ('length_required',),
    412: ('precondition_failed', 'precondition'),
    413: ('request_entity_too_large',),
    414: ('request_uri_too_large',),
    415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
    416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
    417: ('expectation_failed',),
    418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
    421: ('misdirected_request',),
    422: ('unprocessable_entity', 'unprocessable'),
    423: ('locked',),
    424: ('failed_dependency', 'dependency'),
    425: ('unordered_collection', 'unordered'),
    426: ('upgrade_required', 'upgrade'),
    428: ('precondition_required', 'precondition'),
    429: ('too_many_requests', 'too_many'),
    431: ('header_fields_too_large', 'fields_too_large'),
    444: ('no_response', 'none'),
    449: ('retry_with', 'retry'),
    450: ('blocked_by_windows_parental_controls', 'parental_controls'),
    451: ('unavailable_for_legal_reasons', 'legal_reasons'),
    499: ('client_closed_request',),
     
    # Server Error.
    500: ('internal_server_error', 'server_error', '/o\', '✗'),
    501: ('not_implemented',),
    502: ('bad_gateway',),
    503: ('service_unavailable', 'unavailable'),
    504: ('gateway_timeout',),
    505: ('http_version_not_supported', 'http_version'),
    506: ('variant_also_negotiates',),
    507: ('insufficient_storage',),
    509: ('bandwidth_limit_exceeded', 'bandwidth'),
    510: ('not_extended',),
    511: ('network_authentication_required', 'network_auth', 'network_authentication'),
     
     

    四. 高级操作

     

    1. 文件上传,使用files参数

    import requests
     
    files = {'file': open('favicon.ico', 'rb')}  //指定文件名为file
    response = requests.post("http://httpbin.org/post", files=files)
    print(response.text)
     
     

    2. 获取cookie

    import requests
     
    response = requests.get("https://www.baidu.com")
    print(response.cookies) //列表形式
    for key, value in response.cookies.items():
        print(key + '=' + value)
     
     

    3. 会话维持

     
    模拟登陆
     
    例子1,在测试网站httpbin.org中实验
    import requests
     
    response = requests.get('http://httpbin.org/cookies')
    print(response.text)
    上面代码返回空,没获得cookie信息,原因是使用了2次requests.get方法,相当于开启了2个浏览器
     
     
    例子2,在同一个浏览器中获得cookie,使用requests.Session()
    import requests
     
    s = requests.Session()
    response = s.get('http://httpbin.org/cookies') //获得cookie
    print(response.text)
    返回结果如下
    {"cookies":{"number":"123456789"}}
     
     

    4. 证书验证,解决https问题

    import requests
     
    response = requests.get('https://www.12306.cn')
    print(response.status_code)
    使用requests.get()方法来访问URL时,如果发现https证书不合法会报SSLError错误,并中断
     
    解决方法为加一个verify=False参数,并禁止警报
    import requests
    from requests.packages import urllib3
    urllib3.disable_warnings()
    response = requests.get('https://www.12306.cn', verify=False)
    print(response.status_code)
     
     
    自己上传证书
    import requests
     
    response = requests.get('https://www.12306.cn', cert=('/path/server.crt', '/path/key'))
    print(response.status_code)
     
     

    5. 代理设置

     
    1)无用户名和密码的代理
    import requests
     
    proxies = {
      "http": "http://127.0.0.1:9743",
      "https": "https://127.0.0.1:9743",
    }
     
    response = requests.get("https://www.taobao.com", proxies=proxies)
    print(response.status_code)
     
    2)有用户名和密码的代理
    import requests
     
    proxies = {
    }
    response = requests.get("https://www.taobao.com", proxies=proxies)
    print(response.status_code)
     
     
    3)不是http,https代理,而是socks代理的情况
    pip3 install 'requests[socks]'
     
    import requests
     
    proxies = {
        'http': 'socks5://127.0.0.1:9742',
        'https': 'socks5://127.0.0.1:9742'
    }
    response = requests.get("https://www.taobao.com", proxies=proxies)
    print(response.status_code)
     
     

    6. 超时设置

    import requests
    from requests.exceptions import ReadTimeout
    try:
        response = requests.get("http://httpbin.org/get", timeout = 0.5)
        print(response.status_code)
    except ReadTimeout:
        print('Timeout')
     
     

    7. 认证设置

    有些网站需要输入用户名和密码才能看到网页内容
     
    方法1
    import requests
    from requests.auth import HTTPBasicAuth
     
    r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', '123')) //传入用户名和密码
    print(r.status_code)
     
    方法2
    import requests
     
    r = requests.get('http://120.27.34.24:9001', auth=('user', '123'))
    print(r.status_code)
     
     

    8. 异常处理

    import requests
    from requests.exceptions import ReadTimeout, ConnectionError, RequestException
    try:
        response = requests.get("http://httpbin.org/get", timeout = 0.5)
        print(response.status_code)
    except ReadTimeout:  //超时捕获这个异常
        print('Timeout')
    except ConnectionError:  //网络有问题时捕获这个异常
        print('Connection error')
    except RequestException:
        print('Error')
     
    参考
  • 相关阅读:
    通过网络方式安装linux的五种方法
    谈FTP服务器攻击技术及其展望 (下)
    谈FTP服务器攻击技术及其展望 (修改中)
    Fedora 14 x64 试用手记
    加固Samba安全三法
    VMWare高可用集群在企业的应用
    Leetcode-1008 Construct Binary Search Tree from Preorder Traversal(先序遍历构造二叉树)
    Leetcode-1006 Clumsy Factorial(笨阶乘)
    Leetcode-1007 Minimum Domino Rotations For Equal Row(行相等的最少多米诺旋转)
    Leetcode-1005 Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)
  • 原文地址:https://www.cnblogs.com/regit/p/9243660.html
Copyright © 2020-2023  润新知