利用Python中的Selenium实现简单的中英互译

1.环境配置 

        安装Chrome浏览器,并在 “关于 Chrome” 界面获取版本信息

6b4aac24f2ab4529af3df4643192646a.png

        下载与浏览器版本号相对应的Chromedriver插件(点击跳转至下载界面),以“128.0.6613.84”的版本示例,实际上只需要标红的前3位版本号与浏览器相对应即可

f5642723079b40598d445fe1ef4d49b1.png

       点击进去后选择与自己的电脑系统相对于的版本下载即可

fc023c02ae3648d9bd5083afe8f75bc8.png

        安装Selenium

pip install selenium

2.具体实现

        导入Selenium包

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep

        指定Chrome浏览器的绝对路径  (单引号内路径自行替换)

option.binary_location = '.\\Google\\Chrome\\Application\\chrome.exe'

        创建 WebDriver 对象,指定ChromeDriver插件的路径,同时运行Chrome浏览器  (单引号内路径自行替换)

wd = webdriver.Chrome(service=Service(r'.\chromedriver.exe'))

        调用 WebDriver 对象的get方法让浏览器打开百度翻译的网页

wd.get('https://fanyi.baidu.com/mtpe-individual/multimodal')

        这时,需要我们手动在浏览器中打开百度翻译网页,通过审查元素的方式分别获取到输入区域和输出区域的Class值,具体操作见视频(点击跳转至视频)

        输入区域:kXQpwTof

        输出区域:u4heFBcZ

        读取用户输入的需要翻译的内容,再利用Class值获取输入区域,将该内容发送到输入区域中

#读取用户输入的需要翻译的内容
input_txt = input()
#利用Class值获取输入区域
input1 = wd.find_element(By.CLASS_NAME, "kXQpwTof")
#将需要翻译的内容发送到输入区域中
input1.send_keys(f"{input_txt}")

        利用Class值获取输出区域,并将输出区域中翻译好的文本打印到终端中

#利用Class值获取输出区域
output1 = wd.find_element(By.CLASS_NAME, "u4heFBcZ")
#将翻译好的内容打印出来
print(output1.text)

 3.最终代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep

#隐藏浏览器界面
option = webdriver.ChromeOptions()
option.add_argument('--headless')

option.binary_location = '.\\Google\\Chrome\\Application\\chrome.exe'
wd = webdriver.Chrome(service=Service(r'.\chromedriver.exe'), options=option)

#以防浏览器还未打开就执行打开百度翻译网页的代码从而出现错误,这里停顿1s
sleep(1)

#提示一次浏览器已经加载好了可以开始输入了
print("程序加载完成!\n")

#设置个循环,多次反复翻译
while 1:
    #将跳转页面的代码放在循环中,每次翻译完后重新加载页面,清空上一次的内容
    wd.get('https://fanyi.baidu.com/mtpe-individual/multimodal')
    
    #读取用户输入的需要翻译的内容
    input_txt = input()
    #利用Class值获取输入区域
    input1 = wd.find_element(By.CLASS_NAME, "kXQpwTof")
    #将需要翻译的内容发送到输入区域中
    input1.send_keys(f"{input_txt}")

    #等待1.5s,防止还未翻译完成就开始读取输出区域的内容从而输出空白内容
    sleep(1.5)
    
    #利用Class值获取输出区域
    output1 = wd.find_element(By.CLASS_NAME, "u4heFBcZ")
    #将翻译好的内容打印出来
    print(output1.text)

    #打印分割线,起个美观的作用
    #print('-' * 50)

 4.效果展示

d6b63ffde32a4e5b9bff985859182274.png

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值