问题描述
我想复制Johns Hopkins Covid dashboard造成的死亡总数。我想使用Selenium,Python和Selenium的chrome驱动程序来完成此操作。死亡人数可以在路径from selenium.webdriver import Chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
with Chrome() as driver:
driver.get('https://coronavirus.jhu.edu/map.html')
driver.implicitly_wait(20) # Waits for 20 s for the entire page to loads.
diplayElement = driver.find_element_by_xpath('//*[@id="ember1915"]/svg/g[2]/svg/text')
下找到。
这是我的脚本:
Unable to locate element: {"method":"xpath","selector":"//*[@id="ember1915"]/svg/g[2]/svg/text"}”.
失败,并显示错误“没有这样的元素:
{{1}}
我要抓取的其他网站也会发生这种情况。
我该如何解决?该错误的原因是什么?
解决方法
具有Johns Hopkins Covid dashboard中死亡总数的元素,即 905,181 ,位于<iframe>
之内,因此您必须:
-
诱导WebDriverWait使所需的帧可用并切换到。
-
为
visibility_of_element_located()
产生WebDriverWait,您可以使用以下任一Locator Strategies:-
使用
XPATH
和get_attribute()
:driver.get('https://coronavirus.jhu.edu/map.html') WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE']"))) print(WebDriverWait(driver,60).until(EC.visibility_of_element_located((By.XPATH,"//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg' and @class='responsive-text-group']//*[name()='g' and @class='responsive-text-label']/*[name()='svg']/*[name()='text']"))).get_attribute("innerHTML"))
-
使用
XPATH
和 text 属性:driver.get('https://coronavirus.jhu.edu/map.html') WebDriverWait(driver,"//*[name()='svg']/*[name()='text' and text()='Global Deaths']//following::div[1]/*[name()='svg']//*[name()='g']/*[name()='svg']/*[name()='text']"))).text)
-
-
控制台输出:
905,181
-
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在How to retrieve the text of a WebElement using Selenium - Python
中找到相关的讨论
参考
您可以在以下位置找到一些相关的讨论