我正在尝试使用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)
`
给我test = []。以前,我已经在所有的抓取项目中使用了beautifulsoup,但我重做了之前的一些项目,以确保我了解Selenium如何工作并且没有问题。
如果有人可以帮我解决这个问题,那么我可以创建一个我可以使用ActionChains悬停的项目列表,并从中提取价格和日期将非常感激。
谢谢!
**** **** EDIT 为了澄清,我查看了许多关于SVG和g元素以及Highcharts的其他帖子,但我仍然缺乏解决这个问题的方法。我已经尝试了很多Xpath(和其他find_elements_by选项),但只能得到两个结果:(1)Xpath有效,但不包含任何元素,或(2)InvalidSelectorException指示我无法定位带有xpath表达式的元素。我认为这归结为仅仅错误地指定了我的Xpath,但我对如何找到正确的Xpath感到茫然。
答案 0 :(得分:2)
您不能使用上面提到的Xpath来定位svg标记内的元素。
可用于创建悬停对象列表的Xpath是:
“// [name()='svg'] // [name()='g'和@ class ='highcharts-markers'] / * [name()='路径']“
我已经编写了一个 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());
}
}
答案 1 :(得分:1)
谢谢! 2年后,我面临一个等效的项目,并使用您的示例来学习如何使用python和Firefox完成工作。 以下代码可能对某些人有用。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Firefox(executable_path=r'path\to\the\geckodriver.exe')
driver.get('http://fuelinsights.gasbuddy.com/Charts')
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "highcharts-markers")))
test = driver.find_elements_by_xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']")
res = []
for el in test:
hover = ActionChains(driver).move_to_element(el)
hover.perform()
date = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(1)")
price = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(4)")
res.append((date[0].text, price[0].text))
“ res”包含:
('Saturday, May 30, 2020', '1.978 $/gal')
('Friday, May 29, 2020', '1.979 $/gal')
('Thursday, May 28, 2020', '1.977 $/gal')
('Wednesday, May 27, 2020', '1.972 $/gal')
('Tuesday, May 26, 2020', '1.965 $/gal')
.......