请帮助在带有selenium的表单框中输入文本



我正在尝试做一个教程,并在python中学习Selenium,但是我似乎无法使用find_element_by_class或find_element_by_XPATH让Selenium键入邮政编码。

我正在使用:

Python v3.9

Chrome v87

这是我正在练习的URL(您可能需要向篮子添加测试项以查看按钮或运行脚本):

https://www.currys.co.uk/app/checkout

这是我当前的点击代码:

# Selenium Tutorial #1
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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
import time
# Open Chromedriver
driver = webdriver.Chrome(r"C:UsersSte1337Desktopchromedriverchromedriver.exe")
# Open webpage
driver.get("https://www.currys.co.uk/gbuk/tv-and-home-entertainment/televisions/televisions/samsung-ue75tu7020kxxu-75-smart-4k-ultra-hd-hdr-led-tv-10213562-pdt.html")
# Click "Accept All Cookies" or ignore if no pop up
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler"))
)
element.click()
except Exception:
pass
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Add to Basket" or refresh page if out of stock
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, "email-desktop"))
)
time.sleep(5)
browser.refresh()
except:
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.GZkwS")
driver.execute_script("arguments[0].click();", button)
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Continue to Basket"
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.sc-fzpjYC.gJohPa")
driver.execute_script("arguments[0].click();", button)
# Wait 3 seconds
driver.implicitly_wait(3)
# Click "Go to checkout"
button = driver.find_element_by_xpath("//button[contains(@data-component, 'Button')][contains(@type, 'button')]")
driver.execute_script("arguments[0].click();", button)
# Type in postcode
search = driver.find_element_by_xpath("//input[contains(@aria-invalid), 'False')][contains@aria-label, 'Postcode Checker')]")
search.send_keys(NG229NU)
search.send_keys(Keys.RETURN)

要标识input元素,请使用locator

XPATH:

//input[@aria-label='Postcode Checker' and @type='search']

CSS选择器:

input[aria-label='Postcode Checker'][type='search']

为了避免同步问题,我建议使用WebDriverWait()并等待element_to_be_clickable()并在输入中输入文本盒子。

search=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//input[@aria-label='Postcode Checker' and @type='search']")))
search.send_keys("NG229NU")
search.send_keys(Keys.RETURN)

您的XPath无效(第一个谓词中有额外的大括号,第二个谓词中没有左括号)。尝试替换

"//input[contains(@aria-invalid), 'False')][contains@aria-label, 'Postcode Checker')]"

"//input[contains(@aria-invalid, 'False')][contains(@aria-label, 'Postcode Checker')]"

相关内容

  • 没有找到相关文章

最新更新