简体   繁体   English

python 使用 selenium webdriver

[英]python using selenium webdriver

I'm trying to open the "digikey" website and use the search bar to send some data.我正在尝试打开“digikey”网站并使用搜索栏发送一些数据。 Here's an example of the code but it looks like the send key is not working.这是代码示例,但看起来发送键不起作用。 I need help.我需要帮助。 Thank you.谢谢你。

import time
from openpyxl import load_workbook
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='C:/Users/amuri/AppData/Local/Microsoft/WindowsApps/PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0/site-packages/chromedriver.exe')
driver.implicitly_wait(3)

url ='https://www.digikey.com/'
driver.get(url)
print(driver.title)
elem = driver.find_element_by_xpath("/html/body/header/div[2]/div[1]/div/div[2]/div[2]/input")
elem.click()
elem.send_keys("myString")
print(elem.text)

For elem use css selector, not long xpath:对于 elem 使用css选择器,不长 xpath:

elem = driver.find_element_by_css_selector("#main-layout-content .header__searchinput")

header__searchinput class is not unique, that's why I used main-layout-content id to as a parent. header__searchinput class 不是唯一的,这就是我使用main-layout-content id 作为父级的原因。

Also add explicit wait:还要添加显式等待:

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

wait = WebDriverWait(driver, timeout=30)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#main-layout-content .header__searchinput")))
elem = driver.find_element_by_css_selector("#main-layout-content .header__searchinput")
elem.click()
elem.send_keys("myString")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM