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‘]=‘1520575049536‘ data[‘sign‘]=‘4514c46c320493ba8c034eaa8d9decaf‘ data[‘doctype‘]=‘json‘ data[‘version‘]=‘2.1‘ data[‘keyfrom‘]=‘fanyi.web‘ data[‘action‘]=‘FY_BY_CLICKBUTTION‘ data[‘typoResult‘]=‘false‘ data[‘ue‘]=‘utf-8‘ data=urllib.parse.urlencode(data).encode(‘utf-8‘) #方法一,先建立head,作为参数传进去 head={} head[‘User-Agent‘]=‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3355.4 Safari/537.36‘ #urllib.request.Request的可以有三个参数,head(必须是字典)可以作为第三个参数 req=urllib.request.Request(url,data,head) response=urllib.request.urlopen(req) html=response.read().decode(‘utf-8‘) target=json.loads(html) print("翻译结果:%s"%target[‘translateResult‘][0][0][‘tgt‘])
################################################################
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‘]=‘1520575049536‘
data[‘sign‘]=‘4514c46c320493ba8c034eaa8d9decaf‘
data[‘doctype‘]=‘json‘
data[‘version‘]=‘2.1‘
data[‘keyfrom‘]=‘fanyi.web‘
data[‘action‘]=‘FY_BY_CLICKBUTTION‘
data[‘typoResult‘]=‘false‘
data[‘ue‘]=‘utf-8‘
data=urllib.parse.urlencode(data).encode(‘utf-8‘)
req=urllib.request.Request(url,data)
#第二种方法,追加head,用add_header
req.add_header(‘User-Agent‘,‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3355.4 Safari/537.36‘)
response=urllib.request.urlopen(req)
html=response.read().decode(‘utf-8‘)
target=json.loads(html)
print("翻译结果:%s"%target[‘translateResult‘][0][0][‘tgt‘])
############################################################
import urllib.request
import random
url =‘http://ip.chinaz.com/‘
#去百度免费ip,找到最新的,在有效期内的,注意是协议和下面的对应起来
iplist=[‘115.58.129.226:8118‘,‘125.75.115.187:61202‘,‘221.229.22.236:8118‘]
proxy_support=urllib.request.ProxyHandler({‘https‘:random.choice(iplist)})
opener=urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
response=urllib.request.urlopen(url)
html=response.read().decode(‘utf-8‘)
print(html)