首页 > 代码库 > python中的requests使用小结

python中的requests使用小结

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

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 = http://www.mamicode.com/{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=http://www.mamicode.com/data, headers=headers)
#POST自定义HEAD提交数据
r = requests.post(https://www.baidu.com, data=http://www.mamicode.com/json.dumps({some: data}))
#POST提交JSON数据

 

python中的requests使用小结