在python中使用selenium和Beauty soup时在搜索框中键入文本

mhd8tkvw  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(262)

通常,下面的代码可以将信息键入搜索栏,但是,它不允许我在此示例上使用.send_keys()。我需要做什么呢?我注意到的一件事是,当我实际单击该框时,class=“hidden added”行在该行末尾添加了一个灰色的“flex”按钮。不确定这意味着什么,或者这是否是下面代码无法工作的原因。

typetextfirst = driver.find_element_by_id("searchRegistry-text")
   typetextfirst.clear()
   typetextfirst.send_keys(row["Name"])

nwsw7zdq

nwsw7zdq1#

在发送文本之前,请尝试单击该元素,如下所示:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 20)

typetextfirst = wait.until(EC.element_to_be_clickable((By.ID, "searchRegistry-text")))
typetextfirst.click()
typetextfirst.send_keys(row["Name"])

如果这仍然不够,请尝试发送带有操作的文本:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)

typetextfirst = wait.until(EC.element_to_be_clickable((By.ID, "searchRegistry-text")))

actions.move_to_element(typetextfirst)
actions.click()
actions.send_keys(row["Name"])
actions.perform()
xpcnnkqh

xpcnnkqh2#

网站中存在一些重复的元素,具有相同的属性 id . 也许这就是造成问题的原因。我试图复制您的场景,并编写了以下代码。一定要让我知道它是否也适合你。

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")

driver = webdriver.Chrome(options=options)
driver.get('https://www.bedbathandbeyond.com/store/giftregistry/registry-search-guest?icid=static_st_2acr1_'
           'weddingregistry_find_24547')

wait = WebDriverWait(driver, 30)
action = ActionChains(driver)

# Press Cancel to Close the initial Popup

try:
    wait.until(EC.visibility_of_element_located((By.XPATH, '(//a[contains(@id,"bx-close-inside-")])[1]'))).click()
except:
    pass

# Perform Search

searchTextbox = wait.until(EC.presence_of_element_located((By.XPATH, '(//input[@id="searchRegistry-text"])[2]')))
action.move_to_element(searchTextbox).click().send_keys("Hello").perform()

# Click on Search Button

save_Button = wait.until(EC.presence_of_element_located((By.XPATH, '(//button[text()="Search"])[2]')))
action.move_to_element(save_Button).click()

希望它能解决你的问题。谢谢

相关问题