Python Selenium无法访问Tableau小部件

2024-04-26 21:57:04 发布

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

我正在尝试使用Python Selenium从this page中提取数据。该表由Tableau呈现。我需要输入一些数据,然后使用下载按钮

有趣的是,我无法从Selenium访问表中的元素。我试着按id、类或xpath查找。我一直被认为是无趣的例外。但是,这些元素是以HTML呈现的,我可以使用inspect工具查看它们。有人知道这是为什么吗?我怎样才能让他们对Selenium可见

EDIT1:这不是加载时间的问题。我尝试了time.sleep(),我也直接与页面交互


Tags: 工具数据id元素htmlselenium时间page
2条回答

这是相当具有挑战性的,因为它有2iframe后跟shadow元素。而且还不止于此。切换到iframe时,没有iframe引用可用于访问shadow元素。您可以参考下面的代码。它设法得到了图表的标题

# Get first iframe and switch to it
root1 = driver.find_element_by_xpath("//div[@itemprop='articleBody']//iframe")
driver.switch_to.frame(root1)

# Grab the shadow element 
shadow = driver.execute_script('return document')

# Get the iframe inside shadow element of first iframe
iframe2 = shadow.find_element_by_xpath("//body/iframe")

# switch to 2nd iframe
driver.switch_to.frame(iframe2)
print("selected 2nd iframe")
shadow_doc2 = driver.execute_script('return document')
print("second iframe")
heading = shadow_doc2.find_element_by_xpath("//div[@class='tab-textRegion-content']/span//span[text()='Cases of Zika Virus Disease']/ancestor::div[2]").text
print(heading)

输出-

enter image description here

我可以看到你的桌子在iFrame里面。首先进入内部,然后尝试刮取表数据

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@src,'zika_Weekly_Agg_tben')]")))

# COde here to scrape  data

driver.switch_to.default_content() # To come out of frame

您需要导入

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

相关问题 更多 >