首页 > 解决方案 > 检索具有自定义 HTML 属性的元素

问题描述

我有以下网站:https : //www.kvk.nl/handelsregister/publicaties/,我想用 Selenium、Scrapy 和 Python 检索登录链接。所以对于相关功能,我有以下代码:

def start_requests(self):
        self.driver = webdriver.Chrome(executable_path=os.path.join(os.getcwd(), "Drivers", "chromedriver.exe"))
        self.driver.get(self.initial_url)
        test = access_page_wait.until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, 'a[data-ui-test-class="linkCard_toegangscode"]')))
    if test.is_displayed():
        print("+1")
    else:
        print("-1")

但是,这似乎不起作用,因为它只等待 15 秒然后停止。它永远不会达到 +1 或 -1。

现在我的问题是,我们如何将硒指向正确的元素。使用 XPATH 似乎也不起作用find_elements_by_xpath("//a[@data-ui-test-class='linkCard_toegangscode']")

我应该使用另一种选择方法吗?如果是,是哪一种?

标签: python-3.xseleniumxpathscrapycss-selectors

解决方案


因为有 Frame 阻止您访问 element.Switch_To iframe 然后访问该元素。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import os
driver = webdriver.Chrome(executable_path=os.path.join(os.getcwd(), "Drivers", "chromedriver.exe"))
driver.get("https://www.kvk.nl/handelsregister/publicaties/")
driver.switch_to.frame(0)
test=WebDriverWait(driver,10).until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, 'a[data-ui-test-class="linkCard_toegangscode"]')))
if test.is_displayed():
    print("+1")
else:
    print("-1")

试试上面的代码。它应该打印出你正在看的东西。


推荐阅读