小甲鱼:爬虫 1

url + lib === urllib

import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
html = response.read()
print(html)

有道翻译点击检查元素:
选择 Network----XHR------Request URL-------From Data
小甲鱼:爬虫 1_第1张图片
小甲鱼:爬虫 1_第2张图片
将data里的数据,添加符号:

data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult']= 'dict'
data['client']= 'fanyideskweb'
data['salt']= '15968850678607'
data['sign']='a002a0944e7b48f4d35241d16f8290d3'
data['lts']='1596885067860'
data['bv']= '02a6ad4308a3443b3732d855273259bf'
data['doctype']= 'json'
data['version']='2.1'
data['keyfrom']= 'fanyi.web'
data['action']='FY_BY_CLICKBUTTION'

全部代码:

import urllib.request
import json

content = input("请输入中文:")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult']= 'dict'
data['client']= 'fanyideskweb'
data['salt']= '15968850678607'
data['sign']='a002a0944e7b48f4d35241d16f8290d3'
data['lts']='1596885067860'
data['bv']= '02a6ad4308a3443b3732d855273259bf'
data['doctype']= 'json'
data['version']='2.1'
data['keyfrom']= 'fanyi.web'
data['action']='FY_BY_CLICKBUTTION'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8') #解码,把utf-8的格式截成unique格式
print(html)
print(json.loads(html)) #载入之后得到一个字典
target = json.loads(html)
print("翻译结果为:%s" % (target['translateResult'][0][0]['tgt']))

你可能感兴趣的:(小甲鱼:爬虫 1)