3

我正在尝试从 html 的以下部分的 onclick 属性中“选择”链接

<span onclick="Javascript:document.quickFindForm.action='/blah_blah'" 
 class="specialLinkType"><img src="blah"></span>

但不能比以下 XPath 更进一步

//span[@class="specialLinkType"]/@onclick

只返回

Javascript:document.quickFindForm.action

关于如何在quickFindForm.actionXPath 中挑选出该链接的任何想法?

4

3 回答 3

1

我在 Java 应用程序中尝试了 XPath,它工作正常:

    import java.io.IOException;
    import java.io.StringReader;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathFactory;

    import org.w3c.dom.Document;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    public class Teste {

        public static void main(String[] args) throws Exception {
            Document doc = stringToDom("<span onclick=\"Javascript:document.quickFindForm.action='/blah_blah'\" class=\"specialLinkType\"><img src=\"blah\"/></span>");
            XPath newXPath = XPathFactory.newInstance().newXPath();
            XPathExpression xpathExpr = newXPath.compile("//span[@class=\"specialLinkType\"]/@onclick");
            String result = xpathExpr.evaluate(doc);
            System.out.println(result);

        }

        public static Document stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new InputSource(new StringReader(xmlSource)));
        }
    }

结果:

Javascript:document.quickFindForm.action='/blah_blah'
于 2011-07-02T01:30:41.930 回答
0

如果 Scrapy 支持 XPath 字符串函数,这将起作用

substring-before(
   substring-after(
      //span[@class="specialLinkType"]/@onclick,"quickFindForm.action='")
   ,"'")

看起来它也支持正则表达式。像这样的东西应该工作

.select('//span[@class="specialLinkType"]/@onclick').re(r'quickFindForm.action=\'(.*?)\'')

警告:我无法测试第二种解决方案,\'在这种情况下,您必须检查单引号的正确转义序列。

于 2011-07-03T02:55:27.560 回答
0

我使用了 xquery,但它在 xpath 中应该是相同的。我使用了一个 xpath 函数“tokenize”,它根据正则表达式 (http://www.xqueryfunctions.com/xq/fn_tokenize.html) 拆分字符串。在这种情况下,我根据“'”拆分字符串

        xquery version "1.0";
        let $x := //span[@class="specialLinkType"]/@onclick
        let $c := fn:tokenize( $x, '''' )
        return $c[2]

在 xpath 中应该是:

        fn:tokenize(//span[@class="specialLinkType"]/@onclick, '''' )[2]
于 2011-07-04T12:56:51.280 回答