我正在尝试从中抓取数据http://fuelinsights.gasbuddy.com/Charts http://fuelinsights.gasbuddy.com/Charts使用Python和Selenium。困难的部分是,只有当鼠标悬停在折线图上的一个点上时,数据才会出现。目前,我的问题是无法创建所有悬停在对象上的列表。到目前为止我的代码如下:
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)
`
这给了我 test=[]。以前,我在所有抓取项目中都使用 beautifulsoup,但我重做了一些以前的项目,以确保我了解 Selenium 的工作原理并且没有出现问题。
如果有人可以帮助我解决这个问题,以便我可以创建一个项目列表,我可以使用 ActionChains 将鼠标悬停在该列表上并从中提取价格和日期,我将不胜感激。
谢谢你!
****编辑****
为了澄清这一点,我查看了许多有关 SVG 和 g 元素以及 Highcharts 的其他帖子,但我仍然缺乏解决此问题的方法。我尝试了许多 Xpath(以及其他 find_elements_by 选项),但只能得出两个结果:(1)Xpath 有效,但不包含任何元素,或(2)InvalidSelectorException 表明我无法找到具有 xpath 表达式的元素。我相信这归结为简单地错误地指定了我的 Xpath,但我不知道如何找到正确的 Xpath。
您不能使用上面提到的 Xpath 来定位 svg 标记内的元素。
可用于创建悬停对象列表的 Xpath 是:
//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']
我写了一个java程序用于获取所有工具提示元素的文本。您可以使用该逻辑并编写相应的Python代码:
1. 获取工具提示元素列表
List <WebElement> highChartElements= driver.findElements(By.xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']"));
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());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)