1.环境配置
安装Chrome浏览器,并在 “关于 Chrome” 界面获取版本信息
下载与浏览器版本号相对应的Chromedriver插件(点击跳转至下载界面),以“128.0.6613.84”的版本示例,实际上只需要标红的前3位版本号与浏览器相对应即可
点击进去后选择与自己的电脑系统相对于的版本下载即可
安装Selenium
pip install selenium
2.具体实现
导入Selenium包
1 2 3 4 | from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from time import sleep |
指定Chrome浏览器的绝对路径 (单引号内路径自行替换)
1 | option.binary_location = '.\Google\Chrome\Application\chrome.exe' |
创建 WebDriver 对象,指定ChromeDriver插件的路径,同时运行Chrome浏览器 (单引号内路径自行替换)
1 | wd = webdriver.Chrome(service = Service(r '.chromedriver.exe' )) |
调用 WebDriver 对象的get方法让浏览器打开百度翻译的网页
这时,需要我们手动在浏览器中打开百度翻译网页,通过审查元素的方式分别获取到输入区域和输出区域的Class值,具体操作见视频(点击跳转至视频)
输入区域:kXQpwTof
输出区域:u4heFBcZ
读取用户输入的需要翻译的内容,再利用Class值获取输入区域,将该内容发送到输入区域中
1 2 3 4 5 6 | #读取用户输入的需要翻译的内容 input_txt = input () #利用Class值获取输入区域 input1 = wd.find_element(By.CLASS_NAME, "kXQpwTof" ) #将需要翻译的内容发送到输入区域中 input1.send_keys(f "{input_txt}" ) |
利用Class值获取输出区域,并将输出区域中翻译好的文本打印到终端中
1 2 3 4 | #利用Class值获取输出区域 output1 = wd.find_element(By.CLASS_NAME, "u4heFBcZ" ) #将翻译好的内容打印出来 print (output1.text) |
3.最终代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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 : #将跳转页面的代码放在循环中,每次翻译完后重新加载页面,清空上一次的内容 #读取用户输入的需要翻译的内容 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中英互译的资料请关注IT俱乐部其它相关文章!