简体   繁体   English

如何使用 Selenium 和 Python 单击元素

[英]How to click on the element using Selenium and Python

I want to click on "create post" button of this element:我想点击这个元素的“创建帖子”按钮:

<div class="l61y9joe j8otv06s a1itoznt qwtvmjv2 kiex77na lgsfgr3h mcogi7i5 ih1xi9zn ippphs35 a53abz89" data-hover="tooltip" data-tooltip-display="overflow" id="js_2f">Create Post</div>

But this id ( id="js_2f" ) has a random value:但是这个 id ( id="js_2f" ) 有一个随机值:

I did it this way but didn't work !我是这样做的,但是没有用!

wait = WebDriverWait(self.browser, 20)
wait.until(EC.element_to_be_clickable((By.XPATH,  "//*[text()='Create Post' and contains(@id, 'js_')]"))).click()

How can i click on it Using Xpath method?如何使用 Xpath 方法单击它?

Following should help:以下应该有帮助:

driver.find_element_by_xpath('//div[contains(text(),"Create Post")]').click()

You can try below xpath with contains你可以试试下面的 xpath contains

//div[contains(text(),'Create Post')]

You can try to perform a click on this element using link text您可以尝试使用链接文本单击此元素

driver.find_element_by_link_text("Create Post")

or或者

driver.find_element_by_xpath("//div[text() = 'Create Post']")

The Create Post button is a JavaScript enabled element, so to click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies : Create Post按钮是启用了JavaScript的元素,因此要单击该元素,您必须为element_to_be_clickable()诱导WebDriverWait并且您可以使用以下任一定位器策略

  • Using CSS_SELECTOR :使用CSS_SELECTOR

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-hover='tooltip'][data-tooltip-display]"))).click()
  • Using XPATH :使用XPATH

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@data-hover='tooltip' and text()='Create Post'][@data-tooltip-display]"))).click()
  • 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