直接上代码:User-Agent 填自己的
#coding=utf-8
import requests
import json
from lxml import etree
class YouDaoTranslateWeb:
def __init__(self):
self.url="http://www.youdao.com/w/eng/{}/#keyfrom=dict2.index"
self.headers = {"User-Agent": "xxx"}
def run(self):
user_input = input("请输入要翻译的内容:")
self.url = self.url.format(user_input)
response = requests.get(url=self.url,headers=self.headers)
strs = response.content.decode()
self.html = etree.HTML(strs)
def get_result(self):
if len(self.html.xpath("//div[@id='results']//div[@id='fanyiToggle']")) > 0 :
result = self.html.xpath("//div[@id='results']//div[@id='fanyiToggle']//p/text()")
result = result[1] if len(result) > 0 else None
elif len(self.html.xpath("//div[@id='results']//div[@class='trans-container']//p/span/a/text()")) > 0:
result = self.html.xpath("//div[@id='results']//div[@class='trans-container']//p/span/a/text()")
result = result[0] if len(result) > 0 else None
else:
results = self.html.xpath("//div[@id='scontainer']//div[@class='title']/span/text()")
results.pop()
result=""
for i in results:
result+=i.strip()+"\r\n"
print("翻译结果是:")
print(result)
if __name__ == '__main__':
while True:
baidu = YouDaoTranslateWeb()
baidu.run()
baidu.get_result()