我想获取数据并在没有标签的情况下对其进行组织。看起来像这样
<table class="SpecTable">
<col width="40%" />
<col width="60%" />
<tr>
<td class="LightRowHead">Optical Zoom:</td>
<td class="LightRow">15x</td>
</tr>
<tr>
<td class="DarkRowHead">Digital Zoom:</td>
<td class="DarkRow">6x</td>
</tr>
<tr>
<td class="LightRowHead">Battery Type:</td>
<td class="LightRow">Alkaline</td>
</tr>
<tr>
<td class="DarkRowHead">Resolution Megapixels:</td>
<td class="DarkRow">14 MP</td>
</tr>
</table>
并且我希望能够提取所有信息字符串,以便我可以仅使用以下内容将其存储在纯文本文件中:
Optical Zoom: 15x Digital Zoom: 6x Battery Type: Alkaline Resolution Megapixels: 14 MP
public static void main(String[] args) {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);
String Url = "http://www.walmart.com/ip/Generic-14-MP-X400-BK/19863348";
driver.get(Url);
List<WebElement> resultsDiv = driver.findElements(By.xpath("//table[contains (@class,'SpecTable')//td"));
System.out.println(resultsDiv.size());
for (int i=0; i<resultsDiv.size(); i++) {
System.out.println(i+1 + ". " + resultsDiv.get(i).getText());
}
我正在使用 Selenium 使用 Java 进行编程,但我无法找出正确的 XPath 表达式。
有人能弄清楚为什么我会在这上面犯错,并且可能会给我一些关于如何正确解析这些数据的指示吗?我对 Selenium 和 XPaths 很陌生,但我需要它来工作。
此外,如果有人有任何好的资源让我快速学习 Selenium 和 XPath,我将不胜感激!
最佳答案
The spec令人惊讶的是,这是一本关于 XPath 的非常的好读物。
你也可以试试 CSS selectors .
无论如何,从表中获取数据的一种方法如下:
// gets all rows
List<WebElement> rows = driver.findElements(By.xpath("//table[@class='SpecTable']//tr"));
// for every line, store both columns
for (WebElement row : rows) {
WebElement key = row.findElement(By.XPath("./td[1]"));
doAnythingWithText(key.getText());
WebElement val = row.findElement(By.XPath("./td[2]"));
doAnythingWithText(val.getText());
}
关于java - 在java中用xpath和selenium解析HTML表格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323884/