简体   繁体   中英

select all anchor tags having onclick using xpath

I want to select all anchor tags on a web page having 'onClick' function defined as an attribute using XPATH. The web page i am targeting has anchor tags like this

<a href="status.php?op=del&amp;status_id=2" onclick="return confirm('Are you sure you want to delete this item?')">Delete</a>

After a lot of searching I found following potential solutions but none of them seem to work. I have tried (and failed)

//a[@onclick|@href]
//a[onclick]
//a[@onclick]
//a/@*[name()='onclick']
./*[onclick]  #this should have selected all nodes with onclick function

I also tried

//a/@onclick

but this only returns the onclick function definition where as i want the entire anchor tag.

Question: How do i get all the anchor tags that have onclick function defined as an attribute using XPATH?

The XPath //a[@onclick] should work.

Try executing this in the console of your browser to alert each anchor:

(function(){
  var withOnclick = document.evaluate('//a[@onclick]', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  var anchor = withOnclick.iterateNext();
  while (anchor) {
    alert(anchor.outerHTML);
    anchor = withOnclick.iterateNext();
  }
}())

如果您使用的是jQuery,则$("a[onclick]")应该可以找到所有带有onclick的锚点

Finally i was able to do it using

//a[@onclick]

Earlier i was applying this on incorrect response object and hence was not able to get the links. To add further, to get the 'url' values one could do:

HtmlXPathSelector(response).select('//a[@onclick]/@href').extract()

this will return the list of all the links that belong to an anchor tag having 'onclick' function defined as an attribute.

Thanks for your answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM