最新有道翻译爬虫教程 (python爬虫)

环境:python3

直接上代码:

#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": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36"}

    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()

2.其它翻译

最新百度翻译爬虫 获取sign(python爬虫) 最新百度翻译爬虫 获取sign(python爬虫)

最新百度翻译爬虫 手机版(python爬虫) 最新百度翻译爬虫 手机版(python爬虫)

猜你喜欢

转载自blog.csdn.net/QYmufeng/article/details/84069017
今日推荐