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

Scrape data not visible in the source file Python

我想抓取网站 https://www.climatechangecommunication.org/climate-change-opinion-map/ 上的数据。我对硒有点熟悉。但是我需要的数据位于地图下方,地图上的工具提示在源文件中不可见。我已经阅读了一些关于使用 PhantomJS 和其他人的帖子。但是,我不确定从哪里开始以及如何开始。有人可以帮助我入门吗?

谢谢, 瑞信

您可以使用此示例代码:

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

元素截图:

说明: 首先,为了能够与地图下方的元素进行交互,您必须切换到 iframe 内容,否则无法与此元素进行交互。然后地图下方的数据在 svg 标签中,这些标签也很重要。为了能够做到这一点,您需要我提供的样本。

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