简体   繁体   English

如何在python中使用硒查找元素

[英]How to find the element using selenium in python

I can't find the element of the html below. 我找不到以下html的元素。

<span class="tabComboBoxName" id="tab-ui-id-1565209097494" aria-hidden="true">20/07/2019</span>

I've tried the following codes: 我尝试了以下代码:

elem = browser.find_elements_by_xpath("//class[@id='tab-ui-id-1565209097494']")
elem = browser.find_elements_by_class_name('tabComboBoxName')
elem = browser.find_elements_by_id('tab-ui-id-1565209097494')

For those tries I got an empty list. 对于这些尝试,我得到了一个空列表。

The element is a dynamically generated element so to locate the element you need to induce WebDriverWait for the desired visibility_of_element_located() and you can use either of the following Locator Strategies : 元素是动态生成的元素,因此要找到所需的元素以诱导WebDriverWait获得所需的visibility_of_element_located()并且可以使用以下任何一种Locator Strategies

  • Using CSS_SELECTOR : 使用CSS_SELECTOR

     element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.tabComboBoxName[id^='tab-ui-id-']"))) 
  • Using XPATH : 使用XPATH

     element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='tabComboBoxName' and starts-with(@id, 'tab-ui-id-')][contains(., '20/07/2019')]"))) 
  • 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 
  1. Make sure that the element doesn't belong to an <iframe> , if it does - you will need to switch_to() the iframe where the element lives prior to attempting to find it 确保该元素不属于<iframe> ,如果它属于-您需要在尝试找到该元素之前将其存在的iframe切换到()
  2. Make sure that the element doesn't belong to ShadowDOM , if it does - you will need to locate the relevant ShadowRoot element, cast it to the WebElement and use find_element() function of the WebElement instead of driver 确保元素不属于ShadowDOM ,如果它-你需要找到相关的ShadowRoot元素,将其转换为WebElement和使用find_element()WebElement的函数,而不是司机
  3. Make sure to use Explicit Wait as it might be the case the element is not immediately available and it's being loaded later via AJAX request 确保使用Explicit Wait ,因为可能无法立即使用该元素,并且稍后会通过AJAX请求将其加载
  4. Try using another locator strategy , for instance you can stick to the element text like: 尝试使用其他定位器策略 ,例如,您可以坚持使用元素文本,例如:

     //span[text()='20/07/2019'] 

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

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