如何在Selenium中找到这些复选框元素

2024-03-28 23:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到Selenium中的复选框on this site

我试过:Xpath、ID、Type、Actionkeys、Text和partial Text。我已经能够发送密钥(user和password)并定位user/pass元素

  • 代码:

  • label for=“acceptTermsAndConditions” class="checkbox-label-margin"> -#I accept the Terms and Conditions

  • xpath-//*[@id=“loginForm”]/div/div[3]/label1

提前谢谢你的帮助,我觉得我在兜圈子


Tags: textdividontypeselenium密钥site
1条回答
网友
1楼 · 发布于 2024-03-28 23:52:57

TL;请参阅下面带有澄清注释的代码

它对您不起作用的原因之一可能是您需要等待窗体呈现、可见和可交互。这可以用Explicit Wait来解决

我注意到的另一个问题是,通过.click()单击“Accept Terms”,因为单击发生在元素的中间,它会在一个单独的选项卡中打开使用条款,这是不需要的。您可以通过使用偏移量单击(0, 0)Action Chains来解决这个问题

至于使用selenium定位器进入复选框,可以通过多种不同的方式来实现。在下面的代码中,我使用CSS选择器来检查label元素的for属性的值

工作代码:

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


driver = webdriver.Chrome()
driver.get('https://onecall.1100.com.au/au-b4-en/Account/Login')

wait = WebDriverWait(driver, 10)

# wait for the form to get visible
login_form = wait.until(EC.visibility_of_element_located((By.ID, 'loginForm')))

# accept terms
accept_terms = login_form.find_element_by_css_selector('label[for=acceptTermsAndConditions]')
ActionChains(driver).move_to_element_with_offset(accept_terms, 0, 0).click().perform()

# keep me logged in
login_form.find_element_by_css_selector('label[for=checkbox2]').click()

# take a screenshot to prove it is working
login_form.screenshot('form.png')

这就是你将在form.png中看到的:

enter image description here

相关问题 更多 >