python requests模塊和 urllib.request模塊


例子:

>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>>  r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>> r.encoding='utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--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 chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h讀</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>\r\n'

 

參考:https://blog.csdn.net/pittpakk/article/details/81218566

Python3中urllib合並了Python2中的urllib和urllib2.

比如urllib2.Request和urllib2.urlopen 在python3中對應urllib.reques中的 Request和urlopen

對應兼容python2和python3的導入方法可以參考如下方法:

try:

    from urllib.request import Request, urlopen

except:

    from urllib2 import Request, urlopen

對於request,urlopen 使用方法

headers = {"Content-Type":"aplication/json"}

url = "http://www.abc.com/post"

req = request(url, headers=headers)

此處也可以使用add_header方法來添加header

data = {"a":"1"}

res = urlopen(req, data=json.dumps(data).encode("utf-8"))

參考網址(proxy, cookie): https://blog.csdn.net/qq_43546676/article/details/88777227


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM