Python/Selenium“没有这样的元素:无法定位元素”

2024-05-23 15:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难在this website上找到元素。我的最终目标是搜集每个国家的记分卡数据。我设想的方法是让selenium单击列表视图(与默认的国家视图相反),并循环进出所有国家概况,一路上收集每个国家的数据。但是,在这个网站上,过去对我有用的在页面上定位元素的方法都是徒劳的

下面是一些概述我的问题的示例代码

from selenium import webdriver

driver = webdriver.Chrome(executable_path= "C:/work/chromedriver.exe")
driver.get('https://www.weforum.org/reports/global-gender-gap-report-2021/in-full/economy-profiles#economy-profiles')

# click the `list` view option
driver.find_element_by_xpath('//*[@id="root"]/div/div[1]/div[2]/div[2]/svg[2]')

正如你所看到的,我只完成了我计划的第一步。我尝试了其他问题的建议,比如添加等待,但没有效果。我看到该站点在我的DOM中已完全加载,但没有XPath可用于我能找到的任何元素。我很抱歉,如果这个问题被贴得太多,但我知道,任何和所有的帮助是非常感谢。谢谢大家!


Tags: 数据方法div视图元素driverseleniumwebsite
2条回答

元素位于iframe中,您需要切换它以访问元素

使用WebDriverWait()等待frame_to_be_available_and_switch_to_it()

driver.get("https://www.weforum.org/reports/global-gender-gap-report-2021/in-full/economy-profiles#economy-profiles")
wait=WebDriverWait(driver,10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iFrameResizer0")))
wait.until(EC.element_to_be_clickable((By.XPATH,"//*[name()='svg' and @class='sc-gxMtzJ bRxjeC']"))).click()

您需要以下导入

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

enter image description here

另一更新:

driver.get("https://www.weforum.org/reports/global-gender-gap-report-2021/in-full/economy-profiles#economy-profiles")
wait=WebDriverWait(driver,10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "iFrameResizer0")))
driver.find_element_by_xpath("//*[name()='svg' and @class='sc-gxMtzJ bRxjeC']").click()

您未正确单击列表视图。你的定位器必须稳定。我检查了一下,它坏了。 因此,要单击图标,请使用WebDriverWait

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

wait = WebDriverWait(driver, timeout=30)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".sc-gzOgki.ftxBlu>.background")))
list_view = driver.find_element_by_css_selector(".sc-gzOgki.ftxBlu>.background")
list_view.click()

接下来,要获取唯一的行定位器,请使用以下css选择器:

.sc-jbKcbu.kynSUT

它将使用所有国家的名单

相关问题 更多 >