简体   繁体   English

如何使用 selenium - python 单击网站上的按钮?

[英]How do I click on a button on a website using selenium - python?

I am trying to click on "Load More" on a page using selenium.我正在尝试使用 selenium 在页面上单击“加载更多”。 I used the below css_selector code:我使用了下面的 css_selector 代码:

element= driver.find_element_by_css_selector('#amscroll-page-2]')
driver.execute_script("arguments[0].scrollIntoView(true);", element)

I am getting the following error.我收到以下错误。

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".amscroll-load-button"}
  (Session info: chrome=83.0.4103.61)

and I used xpath code:我使用了 xpath 代码:

elemnent=driver.find_element_by_xpath('//*[@id="amscroll-page-2"]')
driver.execute_script("arguments[0].scrollIntoView();", element)
time.sleep(5)
login=element.click()

i am getting the following error我收到以下错误

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <div class="amscroll-page loading" id="amscroll-page-2" rel="2">...</div> is not clickable at point (382, 18). Other element would receive the click: <div class="naaod__content">...</div>
  (Session info: chrome=83.0.4103.61)

The html code of where till where i want to scroll down and click is: html 代码在哪里直到我想向下滚动并单击是:

    <div class="amscroll-page loading" id="amscroll-page-2" rel="2"><input type="button" 
class="amscroll-load-button" style="background: #2675C2;" onclick="amscroll_object.loadNextPage(2);" value="Load More"></div>

There is a load more button over here which i want to click on using selenium.这里有一个加载更多按钮,我想使用 selenium 单击它。

To do that you should use the click() function from the selenium module.为此,您应该使用selenium模块中的click() function。 We will find the button by a CSS selector - this will decrease the chances that the wrong element will be clicked我们将通过CSS selector找到按钮 - 这将减少点击错误元素的机会

self.webdriver.find_element_by_css_selector('input[class="amscroll-load-button"]').click()

However, I would recommend using that code但是,我建议使用该代码

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

WebDriverWait(self.webdriver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[class="amscroll-load-button"]'))).click()

This code checks for the button to be clickable X seconds, and if it does it will be clicked.此代码检查按钮是否可点击 X 秒,如果是,它将被点击。

I was able to solve this by using the following code:我能够通过使用以下代码来解决这个问题:

button = driver.find_element_by_xpath("/html/body/div[3]/div/div[1]/div[2]/div[2]/div[2]/div[3]/div[1]")
ActionChains(driver).move_to_element(button).click(button).perform()

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

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