如何使用selenium python单击网站中存在的所有加号?

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

在下面的链接中,如何单击selenium python中的所有加号?

https://www.screener.in/company/HAL/

我想单击下面屏幕截图中给出的所有 + 按钮?

enter image description here

尝试了多种方式,但我无法超越 driver.get

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

driver = webdriver.Chrome()
driver.get('https://www.screener.in/company/ADANIENT/consolidated/')

python selenium-webdriver
1个回答
0
投票

该网站有某种针对网络爬虫的保护措施,因此您必须最大化浏览器窗口(如果尚未最大化),这样您就不会收到错误消息,告诉您某些其他元素将收到点击 .

除此之外,我的 XPATH 查询仍然会拾取一些隐藏的 plus sign 按钮,这些按钮仅显示在检查器中,但在网页上不可见,随后被 Selenium 捕获为“不可交互”)。

总共有 23 个这样的按钮,以下代码捕获所有可见的 19 个:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementNotInteractableException  # To catch our culprit(s)

driver = webdriver.Chrome()
driver.maximize_window()  # To make sure elements are accessible
driver.get('https://www.screener.in/company/ADANIENT/consolidated/')

WebDriverWait(driver, 2).until(
    EC.presence_of_all_elements_located(
        (By.XPATH, "//span[@class='blue-icon']"))
)

blue_icons = driver.find_elements_by_xpath("//span[@class='blue-icon']/ancestor::button")
clicked = 0
for icon in blue_icons:
    try:
        # time.sleep(0.1) # Optional
        icon.click()
        clicked += 1
    except Exception as e:
        print(e)

print(f"{clicked} `+` buttons clicked.\n{len(blue_icons)-clicked} not interactable.")
© www.soinside.com 2019 - 2024. All rights reserved.