Python Selenium 按键问题

问题描述 投票:0回答:1

我正在尝试使用拼字词典此处设置一些批量查找。通常这需要在左侧的搜索框中输入内容,然后单击其下方的“пошук”按钮:

enter image description here

有三个元素似乎与我相关。

search_bar = driver.find_element(By.ID, "ContentPlaceHolder1_tsearch")
search_button = driver.find_element(By.ID, "ContentPlaceHolder1_search")
current_word = driver.find_element(By.CLASS_NAME, "word_style")

第一个是搜索栏输入元素;第二个是其下方的搜索 (пошук) 按钮;第三个对应于页面右侧填充结果中包含搜索词的元素:

enter image description here

我尝试根据答案模拟按键here,但以下代码似乎没有将结果从“привіт”(默认值)更改为搜索词“людина”。如果有人能够看到我搞砸的事情,我将不胜感激的帮助:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

url = "https://lcorp.ulif.org.ua/dictua/"

op = webdriver.ChromeOptions()
op.add_argument('headless')

driver = webdriver.Chrome(options=op)
driver.get(url)

search_bar = driver.find_element(By.ID, "ContentPlaceHolder1_tsearch")
search_button = driver.find_element(By.ID, "ContentPlaceHolder1_search")

search_bar.clear()
search_bar.send_keys("людина")

ActionChains(driver).move_to_element(search_button).click(search_button).key_down(Keys.CONTROL).key_up(Keys.CONTROL).perform()

current_word = driver.find_element(By.CLASS_NAME, "word_style")
print(current_word.text) # привіт, not людина
python selenium-webdriver
1个回答
0
投票

问题是您的硒脚本太快,无法读取打印的文本。您的 selenium 脚本应该在单击按钮后等待几毫秒,直到您阅读文本。

选项 1:只需在单击搜索按钮和获取文本之间添加一点等待,如下所示:

ActionChains(driver).move_to_element(search_button).click(search_button).key_down(Keys.CONTROL).key_up(Keys.CONTROL).perform()
time.sleep(2)
current_word = driver.find_element(By.CLASS_NAME, "word_style")

您需要进口:

import time

选项 2:使用 Selenium 的 waits,如下所示:

ActionChains(driver).move_to_element(search_button).click(search_button).key_down(Keys.CONTROL).key_up(Keys.CONTROL).perform()
current_word = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(((By.XPATH, "//span[text()='люди́на ']"))))

您需要进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
© www.soinside.com 2019 - 2024. All rights reserved.