- 使用requests发送POST请求
- 使用代理
使用requests发送POST请求
使用场景:
登录注册(POST比GET安全)
需要传输大文本内容(POST请求对长度没有要求)
用法:
response = requests.post(url,data = data,headers=headers)
data为字典
【demo05】向翻译网站发送post请求
请求数据:
f: auto
t: auto
w: 【输入的文字】
响应数据:
content: {
from: "zh-CN",
to: "en-US",
out: 【翻译结果】,
vendor: "ciba", err_no: 0
word_mean: [【翻译结果】]
0: 【翻译结果】
}
代码
import json
import requests
class King(object):
def __init__(self, word):
self.word = word
self.url = 'http://fy.iciba.com/ajax.php?a=fy'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36'}
self.post_data = {
'f': 'auto',
't': 'auto',
'w': self.word
}
def get_data(self):
response = requests.post(self.url, data=self.post_data, headers=self.headers)
return response.content
def parse_data(self, data):
# 将json数据转化为python字典
dict_data = json.loads(data)
# 打印翻译结果
try:
print(dict_data['content']['out'])
except:
print(dict_data['content']['word_mean'][0])
def run(self):
data = self.get_data()
# 解析返回的数据
self.parse_data(data)
if __name__ == '__main__':
while True:
word = input()
king = King(word)
king.run()
使用代理
原因:
让服务器以为不是同一个客户端在请求
防止我们的真实地址被泄露,防止被追究
正向代理与反向代理:
正向代理:浏览器知道服务器的真实地址,例如VPN
反向代理:浏览器不知道服务器的真实地址,例如nginx
使用:
requests.get(url, proxies = proxies)
proxies是字典
proxies = {
"http": "http://12.34.56.79:9527",
"https": "https://12.34.56.79:9527",
}
代理分类
透明代理(Transparent Proxy):“隐藏”IP地址,但可以查到你是谁
匿名代理(Anonymous Proxy):别人知道你用了代理,无法知道你是谁
高匿代理(Elite proxy或High Anonymity Proxy):别人根本无法发现你是在用代理,所以是最好的选择
请求使用的协议可以分为:
http代理
https代理
socket代理等
不同协议的url地址,需要使用不同的代理去请求