Python利用Selenium实现简单的中英互译功能
1.环境配置
安装Chrome浏览器,并在 “关于 Chrome” 界面获取版本信息

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

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

安装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.效果展示

以上就是Python利用Selenium实现简单的中英互译功能的详细内容,更多关于Python Selenium中英互译的资料请关注脚本之家其它相关文章!
相关文章
python 实现rolling和apply函数的向下取值操作
这篇文章主要介绍了python 实现rolling和apply函数的向下取值操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-06-06
Python Flask实现多文件项目打包部署(Linux+Docker+Windows全环境)指南
针对多 .py 文件的 Flask 项目,本文在原有部署方案基础上,补充多文件项目结构规范、Windows 环境部署、跨平台打包等核心内容,有需要的小伙伴可以了解下2026-01-01
python神经网络tf.name_scope和tf.variable_scope函数区别
这篇文章主要为大家介绍了python神经网络tf.name_scope和tf.variable_scope函数的使用区别,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-05-05


最新评论