1

我是 xpath 表达式的初学者,

我有以下网址:

http://www.newark.com/white-rodgers/586-902/contactor-spst-no-12vdc-200a-bracket/dp/35M1913?MER=PPSO_N_P_EverywhereElse_None

它包含 html 页面内容,使用以下 xpath 会在 javascript 中产生相同的 ul 元素:

  1. //*[@id="moreStock_5257711"]
  2. //*[@id="priceWrap"]/div[1]/div/a/following-sibling::ul
  3. //html/body/div/div/div/div/div/div/div/div/div/div/a/following-sibling::ul

使用这个 xpaths 我应该如何在 java 中获得相同的 ul 元素

我曾尝试使用“html 清洁器”,但它在 xpath 中失败了 -

"//*[@id="priceWrap"]/div[1]/div/a/following-sibling::ul",
"//html/body/div/div/div/div/div/div/div/div/div/div/a/following-sibling::ul"

它适用于“//* [@id ='moreStock_5257711']”这个xpath。所以下面我在html清洁器中尝试过的代码

package com.test.htmlcleaner.HtmlCleaner;

import java.io.IOException;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Test {
 public static void main(String[] args) {

  try {
 HtmlCleaner htmCleaner = new HtmlCleaner();
   CleanerProperties cleanerProperties = htmCleaner.getProperties();
   cleanerProperties.setTranslateSpecialEntities(true);
   cleanerProperties.setTransResCharsToNCR(true);
   cleanerProperties.setOmitComments(true);

   String s = "http://www.newark.com/white-rodgers/586-902/contactor-spst-no-12vdc-200a-bracket/dp/35M1913?MER=PPSO_N_P_EverywhereElse_None"; 
     Document doc = Jsoup.connect(s).timeout(30000).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2").get();

    String pageContent=doc.toString();
    TagNode node = htmCleaner.clean(pageContent);
    Object[] statsNode = node.evaluateXPath("//*[@id='moreStock_5257711']");
    if(statsNode.length > 0) {    
             for(int i=0;i<statsNode.length;i++){
               TagNode resultNode = (TagNode)statsNode[i];
               System.out.println("hi");
                System.out.println("Element Text : " +resultNode.getText().toString().trim());                 
               }
          }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (XPatherException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

我要求所有 xpath 都应该使用 java 中的一个包

任何人都可以建议我使用 java 获取 ul 元素的所有 xpaths 表达式。

感谢您的提前问候。

4

1 回答 1

1

尝试调试由 HtmlCleaner 创建的实际 HTML DOM 树。使用以下代码:

String pageContent = doc.toString();
TagNode node = htmCleaner.clean(pageContent);

StringWriter buffer = new StringWriter();
node.serialize(new PrettyHtmlSerializer(cleanerProperties), buffer);

System.out.println(buffer.toSting());

现在,尝试在此缓冲区输出上应用所有 XPath,看看它们为什么不起作用。

于 2015-02-25T08:48:04.950 回答