简体   繁体   English

如何使用 Selenium 和 Python 查找元素

[英]How to find element using Selenium and Python

Just starting to learn selenium using python and running into trouble with the basics of finding elements.刚开始使用 python 学习 selenium 并在查找元素的基础知识方面遇到了麻烦。 This is a search/text box that I am trying to click into and send text to it.这是一个搜索/文本框,我试图单击它并向其发送文本。

Here is the code of the element I got from Edge.这是我从 Edge 获得的元素的代码。

<div class="box" id="ClinicSrch" style="display:block">
  <span align="lb">Last:</span> 
<input type="search" name="NameLast" size="15" class="white1" value="" maxlength="25">
  &nbsp;First: <input type="search" name="NameFirst" size="15" class="white1" value="" maxlength="25"><br>

Here is my code:这是我的代码:

driver.find_element(By.XPATH, '//*[@id="ClinicSrch"]/input[1]').click()

The xpath that I get when copying the element from edge inspect tool is:从边缘检查工具复制元素时得到的 xpath 是:

//*[@id="ClinicSrch"]/input[1]

Full xpath is:完整的 xpath 是:

/html/body/form/div[1]/div[1]/input[1]

I've been trying with other fields and buttons where I have similar xpaths but nothing is working.我一直在尝试使用其他具有类似 xpath 但没有任何效果的字段和按钮。 I always get no such element.我总是没有这样的元素。

To locate the Last Name search field you can use either of the following locator strategies :要定位姓氏搜索字段,您可以使用以下任一定位器策略

  • Using css_selector :使用css_selector

     element = driver.find_element(By.CSS_SELECTOR, "input[name='NameLast']")
  • Using xpath :使用xpath

     element = driver.find_element(By.XPATH, "//input[@name='NameLast']")

Ideally, to locate the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies :理想情况下,要定位可点击元素,您需要为element_to_be_clickable()引入WebDriverWait ,您可以使用以下任一定位器策略

  • Using CSS_SELECTOR :使用CSS_SELECTOR

     element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='NameLast']")))
  • Using XPATH :使用XPATH

     element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='NameLast']")))
  • Note : You have to add the following imports:注意:您必须添加以下导入:

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

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

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