在源文件Python中不可见的刮取数据

2024-04-20 05:06:25 发布

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

我想在网站https://www.climatechangecommunication.org/climate-change-opinion-map/上搜集数据。我对硒有点熟悉。但是我需要的数据在地图下面,地图上的工具提示在源文件中不可见。我读过一些关于使用PhantomJS和其他的帖子。但是,我不知道从哪里开始,如何开始。有人能帮我开始吗。你知道吗

谢谢你, 雷克森


Tags: 工具数据httpsorgmap网站www地图
1条回答
网友
1楼 · 发布于 2024-04-20 05:06:25

您可以使用以下示例代码:

from selenium import webdriver
from selenium.webdriver.support.wait 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.climatechangecommunication.org/climate-change-opinion-map/")

# switch to iframe
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[@src = 'https://environment.yale.edu/ycom/factsheets/MapPage/2017Rev/?est=happening&type=value&geo=county']")))

# do your stuff
united_states = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='document']/div[4]//*[name()='svg']")))
print(united_states.text)

# switch back to default content
driver.switch_to.default_content()

输出:

50%
No
12%
Yes
70%
United States

元素截图:

img

解释:首先,要与地图下方的元素交互,必须切换到iframe内容,否则无法与这些元素交互。那么地图下面的数据就在svg标记中,这些标记也不平凡。为了能够做到这一点,你的样品,我提供了。你知道吗

PS:我在代码中使用了WebDriverWait。使用WebDriverWait您的代码会变得更快速和稳定,因为Selenium会等待特定元素的visibilityclickable等特定条件。在示例代码中,驱动程序至少等待10秒钟,直到满足预期条件。你知道吗

相关问题 更多 >