Let*_*gie 3 python selenium hover
我正在尝试使用 Python 和 Selenium从http://fuelinsights.gasbuddy.com/Charts 中抓取数据。困难的部分是数据仅在折线图上的一个点悬停时才会出现。目前,我的问题是无法创建所有悬停在对象上的列表。到目前为止,我的代码如下:
from selenium import webdriver as web
from selenium.webdriver.common.action_chains import ActionChains
driver = web.Chrome('driver path')
driver.get('http://fuelinsights.gasbuddy.com/Charts')
test= driver.find_elements_by_xpath('//*[@class="highcharts-markers"]')
print(test)
Run Code Online (Sandbox Code Playgroud)
`
这给了我 test=[]。以前,我在所有抓取项目中都使用过 beautifulsoup,但我重做了一些以前的项目,以确保我了解 Selenium 的工作原理并且没有出现问题。
如果有人能帮我解决这个问题,这样我就可以创建一个我可以使用 ActionChains 悬停并从中提取价格和日期的项目列表,我将不胜感激。
谢谢!
****编辑**** 澄清一下,我已经查看了许多其他关于 SVG 和 g 元素以及 Highcharts 的帖子,但我仍然缺乏解决这个问题的方法。我尝试了许多 Xpath(和其他 find_elements_by 选项),但只能得出两个结果:(1) Xpath 有效,但不包含任何元素,或 (2) InvalidSelectorException 表明我无法定位具有 xpath 表达式的元素。我相信这归结为只是错误地指定了我的 Xpath,但我不知道如何找到正确的 Xpath。
小智 5
您不能使用上面提到的 Xpath 来定位 svg 标签内的元素。
可用于创建悬停对象列表的 Xpath 是:
//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']
Run Code Online (Sandbox Code Playgroud)
我编写了一个java 程序来获取所有工具提示元素的文本。您可以使用该逻辑并编写相应的python代码:
1. 获取工具提示元素列表
List <WebElement> highChartElements= driver.findElements(By.xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']"));
Run Code Online (Sandbox Code Playgroud)
2. 遍历列表并使用动作类移动和单击所有工具提示元素
3. 获取工具提示元素的文本。
for(WebElement element:highChartElements){
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();
Thread.sleep(3000);
List<WebElement> highChartToolTipTextElements= driver.findElements(By.xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-tooltip']/*[name()='text']/*[name()='tspan']"));
for(WebElement toolTipElement:highChartToolTipTextElements){
System.out.println("The text for the elements is"+toolTipElement.getText());
}
}
Run Code Online (Sandbox Code Playgroud)