python Selenium找到按钮但无法单击它

qvtsj1bj  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(198)

我正在为Motley Fool网站写一个网络刮刀。该网站有一个“加载更多文章”的按钮。该按钮是可点击的,直到所有的文章加载完毕,然后消失。使用我的代码,按钮被找到并启用,但无法单击。我已经使用了xpath,name,css选择器和更多/更少特定的xpath,希望它被点击,但似乎没有任何工作。这是我的这个函数的代码片段:

url=https://www.fool.com/quote/nasdaq/aep/
driver.get(url)
wait = WebDriverWait(driver, 20)
try:
 while(driver.find element(By.XPATH,'/html/body/div[8]/div[2]/div[1]/section[2]/div/div[1]/div[2]/div[4]/div[3]/div[1]/button').is displayed()):          
      element=driver.find_element(By.XPATH,'/html/body/div[8]/div[2]/div[1]/section[2]/div/div[1]/div[2]/div[4]/div[3]/d iv[1]/button')
      driver.execute_script("arguments[0].scrollIntoView();", element)
      button = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[8]/div[2]/div[1]/section[2]/div/div[1]/div[2]/div[4]/div[3]/div[1]/button')))
      print(button.text)
      print(button.is_enabled())
      driver.execute_script("arguments[0].click()", button)
      time.sleep(3)
except:
  pass

任何想法将不胜感激。谢谢你!

2sbarzqh

2sbarzqh1#

试试这个

from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
url = "https://www.fool.com/quote/nasdaq/aep/"
driver.get(url)
wait = WebDriverWait(driver, 20)
viewMoreButton = '//span[text()="View More AEP Articles"]'
try:
    while (driver.find_element(By.XPATH,
                               viewMoreButton).is_displayed()):
        element = driver.find_element(By.XPATH,
                                      viewMoreButton)
        driver.execute_script("arguments[0].scrollIntoView();", element)
        button = wait.until(EC.element_to_be_clickable(
            (By.XPATH, viewMoreButton)))
        print(button.text)
        print(button.is_enabled())
        driver.execute_script("arguments[0].click()", button)
        time.sleep(3)
except:
    pass

相关问题