![](/img/trans.png)
[英]How to click on an element that is not a button using Selenium in Python
[英]How to click on this button element using Selenium and Python
这是完整的代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Edge(executable_path = r"C:\Users\H\Desktop\Automated_Tasks\msedgedriver.exe") # Modify the path here...
# Navigate to URL
driver.get("https://powerusers.microsoft.com/t5/notificationfeed/page")
#accept cookies
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/center/div[1]/div/div[2]/button[1]"))).click()
#click button
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='lia-button lia-button-primary view-more-icon lia-link-ticket-post-action' and @id='viewMoreLink'][contains(@href, 'notificationList')]/span[text()='Show more']"))).click()
以下行:
button=WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "viewMoreLink"))).click()
给出错误:
File C:\Program Files\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py:249 in check_response
raise exception_class(message, screen, stacktrace)
ElementClickInterceptedException: element click intercepted: Element is not clickable at point (476, 1865)
(Session info: MicrosoftEdge=109.0.1518.61)
这是我尝试单击的按钮的 HTML。
<a onclick="return LITHIUM.EarlyEventCapture(this, 'click', true)" class="lia-button lia-button-primary view-more-icon lia-link-ticket-post-action" data-lia-action-token="gY01pJ4IhqNcqA8Ouq1d20HgZFI9CVTHrEYgxObqxWantjAxFsOxTacdu8LdHjd0" rel="nofollow" id="viewMoreLink" href="https://powerusers.microsoft.com/t5/notificationfeed/page.notificationlist.notificationlistitems.viewmorelink:viewmore/notificationfeed.lastLoadedTimestamp/1674422253100/notificationfeed.lastViewedTimestamp/1674505573710/container_element/notificationList"><span>Show more</span></a>
这是一张显示所需元素所在位置的图片:
根据给定的 HTML 单击带有显示更多文本的元素,您需要为element_to_be_clickable()引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.lia-button.lia-button-primary.view-more-icon.lia-link-ticket-post-action#viewMoreLink[href$='notificationList'] > span"))).click()
使用XPATH :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='lia-button lia-button-primary view-more-icon lia-link-ticket-post-action' and @id='viewMoreLink'][contains(@href, 'notificationList')]/span[text()='Show more']"))).click()
注意:您必须添加以下导入:
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.