开发者

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

开发者 https://www.devze.com 2024-08-28 09:16 出处:网络 作者: aaaaac_
目录1.环境配置 2.具体实现3.最终代码4.效果展示1.环境配置  安装Chrome浏览器,并在 “关于 Chrome” 界面获取版本信息
目录
  • 1.环境配置 
  • 2.具体实现
  • 3.最终代码
  • 4.效果展示

1.环境配置 

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

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

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

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

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

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

安装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

输出区域:uphp4heFBcZ

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

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

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

#利用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'PurFXGnfM), 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 Seleniumwww.devze.com中英互译的资料请关注编程客栈(www.devze.com)其它相关文章!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号