python爬虫,百度翻译
coding=utf-8“”"author:leifunction:百度翻译“”"import jsonimport requestsclass Baidu(object):def __init__(self, word):self.url = "https://fanyi.baidu.com/sug"self.headers = {"User-Agent": "Mozilla/5.0 (Wind
·
coding=utf-8
“”"
author:lei
function:百度翻译
“”"
import json
import requests
class Baidu(object):
def __init__(self, word):
self.url = "https://fanyi.baidu.com/sug"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
}
self.data = {"kw": word}
# 使用post方法发送一个post请求,data为请求体的字体
def get_data(self):
response = requests.post(self.url, data=self.data, headers=self.headers)
return response.content
def parse_data(self, data):
# loads方法将json字符串转换为python字典
dict_data = json.loads(data)
try:
print(dict_data["data"][0]['k'], "对应翻译的结果为:", dict_data["data"][0]['v'])
except:
end = [i["v"].split(";")[0] for i in dict_data["data"]]
print(self.data, "对应翻译的结果为:", end)
def run(self):
"""
编写爬虫逻辑
:return:
"""
# url
# headers
# data字典
# 发送请求获取响应
response = self.get_data()
print(response)
# 数据解析
self.parse_data(response)
if name == ‘main’:
word = input(“请输入要翻译的单词或句子:”)
bai = Baidu(word)
bai.run()
更多推荐
已为社区贡献3条内容
所有评论(0)