如何使用selenium翻译单词

环境搭建

1、pip install selenium

2、下载浏览器驱动,放在python解释器所在的文件夹下

 

from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
import time

word = input('输入单词:')


def MySelenium(a):
    website = Firefox()
    website.get(f"https://fanyi.baidu.com/?aldtype=85#en/zh/{a}")  # 对应单词的网址
    time.sleep(1)
    adelement = website.find_element(By.XPATH, "/html/body/div[1]/div[7]/div/div/div[3]/span")  # 广告
    adelement.click()  # 点击去除广告
    PhoneticSymbols = website.find_element(By.XPATH, "/html/body//span[@class='phonetic-transcription']/b").text  # 音标
    annotations = website.find_element(By.XPATH, "/html/body//div[@class='dictionary-comment']").text  # 注释
    website.close()
    # 是每个单词的音标处的xpath不同
    file = open('word', 'a', encoding='utf-8')  # 防止乱码
    file.write('\n')
    file.write(a)
    file.write(PhoneticSymbols)
    file.write('\n')
    file.write(annotations)
    file.close()
    print(a)
    print(PhoneticSymbols)
    print(annotations)
    file.close()
    return


MySelenium(word)

 

无头浏览器的参数封装

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options

# 准备好参数配置
option = Options()
option.add_argument("--headless")
option.add_argument("--disbale-gpu")
website = Firefox(options=option)  # 把参数配置设置到浏览器中

 

键盘控制

from selenium.webdriver.common.keys import Keys

 

posted @ 2022-05-09 19:55  树叶本子  阅读(79)  评论(0)    收藏  举报