美文网首页
python3 爬虫 requests

python3 爬虫 requests

作者: qiaoqiao123 | 来源:发表于2019-04-11 12:40 被阅读0次

    请求网页

    常用的库有requests和urllib

    html的请求方式:

    • get
    • post
    • put
    • delete
    • head
    • options

    requests

    • GET请求
    • headers --- headers={'User-Agent':''}
    • POST --- requests.post('',data=data)
    • 响应
    • Cookie --- headers={'Cookie':''}
    • Session --- s = requests.Session()
    • SSL ---- SSL
    • 代理设置 --- 代理 proxies
    • 超时设置 --- timeout
    • 身份认证 --- auth
    • Prepared Request --- 请求看成独立对象

    GET请求

    基本的get请求,requests.get('http://httpbin.org/get').text,返回:

    {
      "args": {}, 
      "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.10.0"
      }, 
      "origin": "122.4.215.33", 
      "url": "http://httpbin.org/get"
    }
    

    r = requests.get(“http://httpbin.org/get?name=germey&age=22”) 中链接由基本url+paraments构成
    可以由get方法里面的params构造出来.

    data = {
        'name': 'germey',
        'age': 22
    }
    r = requests.get("http://httpbin.org/get", params=data)
    print(r.text)
    
    # 返回
    {
      "args": {
        "age": "22", 
        "name": "germey"
      }, 
      "headers": {
        "Accept": "*/*", 
        "Accept-Encoding": "gzip, deflate", 
        "Host": "httpbin.org", 
        "User-Agent": "python-requests/2.10.0"
      }, 
      "origin": "122.4.215.33", 
      "url": "http://httpbin.org/get?age=22&name=germey"
    }
    

    加入headers

    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'
    }
    r = requests.get("https://www.zhihu.com/explore", headers=headers)
    

    POST请求

    • data 提交表单
    data = {'name': 'germey', 'age': '22'}
    r = requests.post("http://httpbin.org/post", data=data)
    

    响应

    使用text和content获取了响应的内容,还有很多属性和方法可以用来获取其他信息,比如状态码、响应头、Cookies等。

    headers和cookies这两个属性得到的结果分别是CaseInsensitiveDict和RequestsCookieJar类型

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

    Cookie

    Cookie 将Cookie放入headers里面

    headers = {
        'Cookie': 'q_c1=31653b264a074fc9a57816d1ea93ed8b|1474273938000|1474273938000; d_c0="AGDAs254kAqPTr6NW1U3XTLFzKhMPQ6H_nc=|1474273938"; __utmv=51854390.100-1|2=registration_date=20130902=1^3=entry_date=20130902=1;a_t="2.0AACAfbwdAAAXAAAAso0QWAAAgH28HQAAAGDAs254kAoXAAAAYQJVTQ4FCVgA360us8BAklzLYNEHUd6kmHtRQX5a6hiZxKCynnycerLQ3gIkoJLOCQ==";z_c0=Mi4wQUFDQWZid2RBQUFBWU1DemJuaVFDaGNBQUFCaEFsVk5EZ1VKV0FEZnJTNnp3RUNTWE10ZzBRZFIzcVNZZTFGQmZn|1474887858|64b4d4234a21de774c42c837fe0b672fdb5763b0',
        'Host': 'www.zhihu.com',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
    }
    r = requests.get('https://www.zhihu.com', headers=headers)
    

    还可以通过cookiejia来设置

    会话维持 Session

    requests中,如果直接利用get()post()等方法的确可以做到模拟网页的请求,但是这实际上是相当于不同的会话,也就是说相当于你用了两个浏览器打开了不同的页面。

    import requests
     
    s = requests.Session()
    s.get('http://httpbin.org/cookies/set/number/123456789')
    r = s.get('http://httpbin.org/cookies')
    print(r.text)
    

    SSL证书验证

    requests提供证书验证的功能。当发送HTTP请求的时候,它会检查SSL证书,我们可以使用verify参数控制是否检查此证书。其实如果不加verify参数的话,默认是True,会自动验证。

    import requests
     
    response = requests.get('https://www.12306.cn', verify=False)
    print(response.status_code)
    

    代理设置

    proxies参数

    import requests
     
    proxies = {
      "http": "http://10.10.1.10:3128",
      "https": "http://10.10.1.10:1080",
    }
     
    requests.get("https://www.taobao.com", proxies=proxies)
    

    若代理需要使用HTTP Basic Auth,可以使用类似http://user:password@host:port这样的语法来设置代理

    import requests
     
    proxies = {
        "http": "http://user:password@10.10.1.10:3128/",
    }
    requests.get("https://www.taobao.com", proxies=proxies)
    

    除了基本的HTTP代理外,requests还支持SOCKS协议的代理

    import requests
    
    proxies = {
        'http': 'socks5://user:password@host:port',
        'https': 'socks5://user:password@host:port'
    }
    requests.get("https://www.taobao.com", proxies=proxies)
    

    超时设置

    import requests
     
    r = requests.get("https://www.taobao.com", timeout = 1)
    print(r.status_code)
    

    请求分为两个阶段,即连接(connect)和读取(read)。

    r = requests.get('https://www.taobao.com', timeout=(5,11, 30))
    

    身份认证

    import requests
    from requests.auth import HTTPBasicAuth
     
    r = requests.get('http://localhost:5000', auth=HTTPBasicAuth('username', 'password'))
    
    r = requests.get('http://localhost:5000', auth=('username', 'password'))
    

    此外,requests还提供了其他认证方式,如OAuth认证,不过此时需要安装oauth包

    Prepared Request

    我们可以将请求表示为数据结构,其中各个参数都可以通过一个Request对象来表示。

    from requests import Request, Session
     
    url = 'http://httpbin.org/post'
    data = {
        'name': 'germey'
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
    }
    s = Session()
    req = Request('POST', url, data=data, headers=headers)
    prepped = s.prepare_request(req)
    r = s.send(prepped)
    

    有了Request这个对象,就可以将请求当作独立的对象来看待,这样在进行队列调度时会非常方便。

    相关文章

      网友评论

          本文标题:python3 爬虫 requests

          本文链接:https://www.haomeiwen.com/subject/jtnaiqtx.html