如何从XPath查询中提取嵌入式属性值的前一个属性值?

2024-10-01 02:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但是不能比下面的XPath更进一步

^{pr2}$

只会返回

Javascript:document.quickFindForm.action

关于如何用XPath从quickFindForm.action中找出链接有什么想法吗?在


Tags: srcimg属性链接htmlactionjavascriptdocument
3条回答

我使用了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中应该是:

^{pr2}$

如果Scrapy支持XPath字符串函数,这就可以了

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

它看起来也支持regex。这样的事情应该行得通

^{pr2}$

注意:我不能测试第二个解决方案,您必须检查\'是否是本例中单引号的正确转义序列。在

我在一个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)));
        }
    }

结果:

^{pr2}$

相关问题 更多 >