[英]can't find stock price in yahoo finance using selenium webdriver
I've been trying to find a way to pull stock data from yahoo finance for the past two days. 在过去的两天里,我一直在尝试寻找一种从Yahoo Finance提取股票数据的方法。 I've used selenium webdriver before and I find it very useful, however I can't seem to get it to locate the price for stocks.
我以前使用过硒网络驱动程序,我发现它非常有用,但是我似乎无法通过它找到股票价格。 The html is rather complicated in finance.yahoo.com but I think you can isolate the tags so my code looks something like this:
html在finance.yahoo.com中相当复杂,但是我认为您可以隔离标签,因此我的代码如下所示:
public void writeSheet() throws WriteException, Exception{
int r = 0;
for(String s : listOfFunds){
Label stockLabel = new Label(0,r,s);
Number stockPrice = new Number(1,r,0.00);
driver.get("http://finance.yahoo.com/q?s=" + s + "%2C+&q1=q");
Thread.sleep(200);
WebElement price = driver.findElement(By.tagName("span"));
stockPrice.setValue(Double.parseDouble(price.findElement(By.id("yfs_184_" + s.toLowerCase())).getText()));
id=\"yfs_184_" + s.toLowerCase() + "\""));
sourceSheet.addCell(stockLabel);
sourceSheet.addCell(stockPrice);
r++;
}
sourceBook.write();
sourceBook.close();
}
I'm really just sort of checking to see I didn't miss anything stupid or if I'm searching by the tag name. 我实际上只是在进行检查,以查看我没有错过任何愚蠢的东西,或者是否正在按标签名称进行搜索。 The one HTML line I'm looking for looks like this:
我要查找的HTML行如下所示:
<span id="yfs_184_" + insert symbol to lowercase here + ">stock price</span>
I tried this and it worked very well. 我尝试了一下,效果很好。
WebElement stockpriceText = driver.findElement(By.cssSelector("span[id=\"yfs_l84_ctsh\"]"));
String price = stockpriceText.getText();
Output: 51.59 输出: 51.59
I believe your locating strategy is a bit wrong. 我相信您的定位策略有误。 You are trying to first find a span in:
您正在尝试首先找到以下范围:
WebElement price = driver.findElement(By.tagName("span"));
which could be the problem. 这可能是问题所在。 WebDriver will find the very first
<span>
element on the page. WebDriver将在页面上找到第一个
<span>
元素。 It could be some other span in the DOM. 这可能是DOM中的其他范围。
Plus when you are executing this: 另外,当您执行此操作时:
price.findElement(By.id("yfs_184_" + s.toLowerCase())).getText();
That time you are trying to find another element inside the span element which will not work. 那时,您试图在span元素内找到另一个将不起作用的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.