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

环境:python3

直接上代码: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()

2.其它翻译

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

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

你可能感兴趣的:(python)