zoukankan      html  css  js  c++  java
  • 网络爬虫day1:python中的request模块基本使用

    1、get和post的区别

    在互联网的世界中,有一个不经常提起但是经常使用的协议:TCP协议。它就好比一个快递公司。不同的浏览器(发起http请求)和服务器(接受http请求)就是不同的传输方式。
    get的方式就相当于快递员使用的小三轮车。
    理论上,你可以在快递车顶堆货物(url中无限加参数)。但是如果在车顶加太多大货物在公路上跑是有非常大的安全风险的,他们会限制单次运输量来控制风险,数据量太大对浏览器和服务器都是很大负担。业界不成文的规定是,(大多数)浏览器通常都会限制url长度在2K个字节,而(大多数)服务器最多处理64K大小的url。超过的部分,恕不处理。如果你用GET服务,在request body偷偷藏了数据,不同服务器的处理方式也是不同的,有些服务器会帮你卸货,读出数据,有些服务器直接忽略,所以,虽然GET可以带request body,也不能保证一定能被接收到哦。
    post协议就相当于一个箱式货车
    那么如何要一次运输的货物非常多,非常大(http参数中传输的数据量大)该怎么办呢?这时候就应该使用POST了,post就相当于一个大货车不用在车顶上装货物了,直接把货物装置到货车里面,这样非常安全。

    python运行代码

    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "wxwinder"
    # __email__ = "wxwinder@qq.com"
    # __website__ = "www.cnblogs.com/bravexz"
    # Date: 2019/3/1
    
    import requests
    r = requests.get("http://www.baidu.com")
    r.encoding='utf-8'
    print('编码类型', r.encoding)
    print('状态码', r.status_code)
    print(r.text)
    
    

    运行结果:

    编码类型 utf-8
    状态码 200
    <!DOCTYPE html>
    <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
    
    
    Process finished with exit code 0
    

    断开Internet后,代码运行报错或者服务器不存在的情况下产生。这种情况下,异常同样会带有"reason"属性,它是一个tuple(可以理解为不可变的数组),包含了一个错误号和一个错误信息。

    requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.baidu.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001ECC5BFAF60>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))
    

    请求头

    请求头信息是能够标识用户所使用的信息,一般在爬虫的时候,如果不添加请求头,可能会被网站禁止访问。为了让目标站点能够访问站点,此时我们就需要添加请求头来进行模拟伪装,使用python添加请求头方法如下:

    headers= {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
    
    }
    payloads ={
        'username':'wef',
        'password':'weifowefjiwe'
    }
    r =requests.post('https://passport.baidu.com/v2/api/?login',headers=headers,data=payloads)
    r.encoding='utf-8'
    print('url信息',r.url)
    print('headers头信息',r.headers)
    print('aaaaaaaaaaaaaaaaaa',r.reason)
    print('bbbbbbbbbbbbbbbbbbb',r.raw.read())
    print(r.text)
    

    输出结果:

    url信息 https://passport.baidu.com/v2/api/?login
    headers头信息 {'Access-Control-Expose-Headers': 'Trace-ID', 'Cache-Control': 'public', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Fri, 01 Mar 2019 01:28:20 GMT', 'Expires': '0', 'Last-Modified': 'Fri, 01 Mar 2019 01:28:19 1MarGMT', 'P3p': 'CP=" OTI DSP COR IVA OUR IND COM ", CP=" OTI DSP COR IVA OUR IND COM "', 'Pragma': 'public', 'Server': 'Apache', 'Set-Cookie': 'PASSID=9dmvyd; expires=Thu, 01-Mar-2018 01:28:19 GMT; path=/; domain=passport.baidu.com; httponly, UBI=fi_PncwhpxZ%7ETaJc8zzkEOCI0Zs32ypT%7EL6; expires=Tue, 18-May-2027 01:28:19 GMT; path=/; domain=passport.baidu.com; httponly, BAIDUID=8B05A288447C6D7390018D3529487652:FG=1; expires=Sat, 29-Feb-20 01:28:19 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1', 'Strict-Transport-Security': 'max-age=31536000', 'Trace-Id': '', 'Tracecode': '16999976160350846986030109, 16999976160438000650030109', 'Vary': 'Accept-Encoding', 'Content-Length': '318'}
    aaaaaaaaaaaaaaaaaa OK
    bbbbbbbbbbbbbbbbbbb b''
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
    <script type="text/javascript">
    
    var url = encodeURI('https://passport.baidu.com/v2Jump.html?callback=&index=0&codestring=&username=&phonenumber=&mail=&tpl=&u=&needToModifyPassword=&gotourl=&auth=&error=100023&traceid=');
    //parent.callback(url)
    window.location.replace(url);
    
    </script>
    </body>
    </html>
    
    
    Process finished with exit code 0
    
    
  • 相关阅读:
    Velocity的使用小记
    fastJson的SerializeFilter使用
    快捷的时间转化
    How to execute a Stored Procedure with Entity Framework Code First
    自定义 ASP.NET Identity Data Model with EF
    Asp.Net Core get client IP
    HTTP 请求头中的 X-Forwarded-For
    HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别
    【逻辑】500桶酒,找毒酒
    Asp.Net Core 输出 Word
  • 原文地址:https://www.cnblogs.com/bravexz/p/10454663.html
Copyright © 2011-2022 走看看