码迷,mamicode.com
首页 > 编程语言 > 详细

python中的requests使用小结

时间:2017-07-15 10:12:36      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:htm   passwd   指南   pip   hid   bin   发送   mozilla   小结   

现接触到的很少,详细的官方教程地址:

requests官方指南文档:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
requests高级指南文档:http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

1.安装request,bs4

pip install requests
pip install bs4

2.代码文档中调用

import requests
from bs4 import BeautifulSoup

3.发送http请求

r = requests.get(‘https://github.com/timeline.json’) #GET请求
r = requests.post(“http://httpbin.org/post”) #POST请求
r = requests.put(“http://httpbin.org/put”) #PUT请求
r = requests.delete(“http://httpbin.org/delete”) #DELETE请求
r = requests.head(“http://httpbin.org/get”) #HEAD请求
r = requests.options(“http://httpbin.org/get”) #OPTIONS请求

4.get方法

r = requests.get(http://dict.baidu.com/s, params={wd:python})  #带参数的GET请求
#等于http://dict.baidu.com/s?wd=python
r = requests.get(URL, params={ip: 8.8.8.8}, timeout=1) #设置超时时间
r = requests.get(https://httpbin.org/hidden-basic-auth/user/passwd, auth=HTTPBasicAuth(user, passwd))  #基本身份认证(HTTP Basic Auth)
r = requests.get(URL, auth=HTTPDigestAuth(user, pass)) #摘要式身份认证(HTTP Digest Auth)
cookies = {testCookies_1: Hello_Python3, testCookies_2: Hello_Requests}
r = requests.get(url, cookies=cookies)
#带cookies的请求
r = requests.get(http://www.baidu.com/link, allow_redirects = False) #禁止URL跳转
proxies = {
  "http": "http://10.10.1.10:3128",
  "http": "http://user:pass@10.10.1.10:3128/",
  "https": "http://10.10.1.10:1080",
}
r = requests.get("http://www.baidu.com", proxies=proxies) #代理访问
headers = {Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,
           Accept-Encoding: gzip, deflate, compress,
           Accept-Language: en-us;q=0.5,en;q=0.3,
           Cache-Control: max-age=0,
           Connection: keep-alive,
           User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0}
r = requests.get(http://www.baidu.com, headers = headers)
#自定义head请求页面

5.POST方法

files = {file: open(/home/1.mpg, rb)}
r = requests.post(url, files=files)
#POST上传文件
data = {some: data}
headers = {content-type: application/json,
           User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0} 
r = requests.post(https://www.baidu.com, data=data, headers=headers)
#POST自定义HEAD提交数据
r = requests.post(https://www.baidu.com, data=json.dumps({some: data}))
#POST提交JSON数据

 

python中的requests使用小结

标签:htm   passwd   指南   pip   hid   bin   发送   mozilla   小结   

原文地址:http://www.cnblogs.com/stuqx/p/7178505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!