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()
您可以使用以下示例代码:
输出:
元素截图:
解释:首先,要与地图下方的元素交互,必须切换到
iframe
内容,否则无法与这些元素交互。那么地图下面的数据就在svg
标记中,这些标记也不平凡。为了能够做到这一点,你的样品,我提供了。你知道吗PS:我在代码中使用了
WebDriverWait
。使用WebDriverWait
您的代码会变得更快速和稳定,因为Selenium会等待特定元素的visibility
或clickable
等特定条件。在示例代码中,驱动程序至少等待10秒钟,直到满足预期条件。你知道吗相关问题 更多 >
编程相关推荐