如何查找并点击网站的按钮?

问题描述 投票:0回答:1

我尝试开发一个基于Selenium的python脚本来操作网站。这是网站: https://www.heatpumpkeymark.com/en/?type=109126&tx_pskeymark_frontend%5Bholder%5D=2482&tx_pskeymark_frontend%5Baction%5D=certificateHolder&tx_pskeymark_frontend%5Bcontroller%5D=Frontend&cHash=1f82e53f3d95d0b9ebfe0c7bb 0cd2月2

我想找到并单击“下载所有子类型的报告”按钮。我在其他网站成功做到了这一点,但在那个网站却失败了。

我的以下脚本不起作用。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

webdriver_path = r'D:\MyWork\driver\chromedriver.exe'

service = Service(webdriver_path)
chrome_options = Options()

url = "https://www.heatpumpkeymark.com/en/?type=109126&tx_pskeymark_frontend%5Bholder%5D=2482&tx_pskeymark_frontend%5Baction%5D=certificateHolder&tx_pskeymark_frontend%5Bcontroller%5D=Frontend&cHash=1f82e53f3d95d0b9ebfe0c7bb0cdfeb2"
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get(url)
time.sleep(3)
wait = WebDriverWait(driver, 5)  

class_name = 'btn btn-primary'
text = 'Download reports for all subtypes'

try:
    # button = wait.until(EC.element_to_be_clickable((By.XPATH, f'//button[class()="{class_name}"]')))
    button = wait.until(EC.element_to_be_clickable((By.XPATH, f'//button[text()="{text}"]')))
    
    if button:
        print('Button found')
    else:
        print('Button not found')

finally:
    driver.quit()```

When running the above script, the error is on the line "button = ...", as following: 
TimeoutException                          Traceback (most recent call last)
Cell In[9], line 29
     25 text = 'Download reports for all subtypes'
     27 try:
     28     # button = wait.until(EC.element_to_be_clickable((By.XPATH, f'//button[class()="{class_name}"]')))
---> 29     button = wait.until(EC.element_to_be_clickable((By.XPATH, f'//button[text()="{text}"]')))
     31     if button:
     32         print('Button found')

File c:\Users\ctran\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\support\wait.py:105, in WebDriverWait.until(self, method, message)
    103     if time.monotonic() > end_time:
    104         break
--> 105 raise TimeoutException(message, screen, stacktrace)

TimeoutException: Message: 
Stacktrace:
    GetHandleVerifier [0x00007FF6268F22C2+60002]
    (No symbol) [0x00007FF62686CA59]
    (No symbol) [0x00007FF626727EDA]
    (No symbol) [0x00007FF6267776E6]
    (No symbol) [0x00007FF6267777AC]
...

Have you any idea to solve the problem? Thank you for your help. 
python-3.x selenium-webdriver web-scraping
1个回答
0
投票

似乎 Xpath 无法访问,我想像这样修复 XPath

(29号线)

button = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div[2]/div[1]/a')))
© www.soinside.com 2019 - 2024. All rights reserved.