Python Requests详细教程
$ pip install requests
$ easy_install requests
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
response = requests.get("https://www.lidihuo.com/python/spider-test.html")
# 也可以这么写
# response = requests.request("get", "https://www.lidihuo.com/python/spider-test.html")
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
kw = {'wd':'爬虫-立地货'}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.text)
# 查看响应内容,response.content返回的字节流数据
print(respones.content)
# 查看完整url地址
print(response.url)
# 查看响应头部字符编码
print(response.encoding)
# 查看响应码
print(response.status_code)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
response = requests.post("https://www.lidihuo.com/python/spider-test.html", data = data)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
formdata = {请求参数}
url = "https://xxxx.com"
headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
response = requests.post(url, data = formdata, headers = headers)
print(response.text)
# 如果是json文件可以直接显示
print(response.json())
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
# 根据协议类型,选择不同的代理
proxies = {
"http": "http://127.0.0.1:8088",
"https": "http://127.0.0.1:8088",
}
response = requests.get("https://www.lidihuo.com/python/spider-test.html", proxies = proxies)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
# 如果代理需要使用HTTP Basic Auth,可以使用下面这种格式:
proxy = { "http": "username:password@ip:port" }
response = requests.get(url, proxies = proxy)
print(response.text)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
auth=(username, password)
response = requests.get(url, auth = auth)
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-20
import requests
response = requests.get("https://www.lidihuo.com/python/spider-test.html", verify=True)
# 也可以省略不写
# response = requests.get("https://www.lidihuo.com/python/spider-test.html")