requests请求分为get请求和post请求。
get请求的常用参数包括:
url=self.url,params=data,headers=self.headers
url -->请求的路径地址(字符串类型)
params-->请求的参数(字典类型)
headers-->设置请求头(字典类型,常常用来设置User-Agent,模拟浏览器登录)
proxies-->设置请求代理(字典类型,格式{'http':'host:port'}或者{'http':['host1:port1','host2:port2',...]})
post请求的常用参数包括(与get的不同在于请求参数的表示不同,post用data,get用params):
url -->请求的路径地址(字符串类型)
data-->请求的参数(字典类型)
headers-->设置请求头(字典类型,常常用来设置User-Agent,模拟浏览器登录)
proxies-->设置请求代理(字典类型,格式{'http':'host:port'}或者{'http':['host1:port1','host2:port2',...]})
post请求实例
参数的常用配置
import requests
url = 'https://cn.bing.com/ttranslationlookup'
data = {
'from': 'en',
'to': 'zh-CHS',
'text': 'apple'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
}
# 配置代理
proxy = {
'http': ['115.223.214.11:9000',
'182.141.42.194:9000'] # 也可以设置为proxy={'http':'155.223.214.11:9000'}
}
r = requests.post(url, data, headers=headers, proxies=proxy)if r.status_code == 200: print('ok')
用云打码对验证码进行破解登录
import requests
import ydm_http
randcode_url = 'https://so.gushiwen.org/RandCode.ashx'
# 创建session对象
s = requests.session()
r = s.get(randcode_url)
if r.status_code == 200:
# 下载图片
with open('randcode.gif', 'wb') as f:
f.write(r.content)
print('验证码图片下载成功')
print('验证码请求之后的cookie: ',r.cookies)
# 获取图片中的内容
randCodeTxt = ydm_http.ydm("randcode.gif")
print(type(randCodeTxt))
print('获取到的验证码: ', randCodeTxt)
# 用户登录
login_url = 'https://so.gushiwen.org/user/login.aspx'
login_data = {
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email': '123456@qq.com',
'pwd': '123456',
'code': randCodeTxt.strip()
}
r = s.post(login_url, data=login_data)
print(r.status_code)
print(r.url)
print(r.text)
requests get请求的回复对象所包含的属性包括:
resp.text:获取网站源码(字符串类型)
resp.encoding:访问或定制编码方式 # 如一般所得网页源码出现乱码的情况下可以设置:resp.encoding='gb2312'
resp.url:获取请求的url
resp.content:获取网站源码,但响应的是字节类型
resp.status_code : 响应的状态码
resp.headers:响应的头信息
resp.json():获取json数据