Find tag with id including [] with Nokogiri

寵の児 提交于 2020-01-12 07:00:50

问题


I have an html element like:

<div id="spam[500]">

I want to search for this element by id, but it seems that nokogiri is getting confused by the []. I'm trying:

doc.css("#spam[#{eggs.id}]")

but to no avail.


回答1:


Chris, try this and let me know if it works:

doc = Nokogiri::HTML(page)
el = doc.xpath("//div[@id='spam[500]']").first

The problem is that you can't access it via CSS (even in the browser). Try setting some CSS attributes for "spam[500]" and they won't be applied. You can access via xpath however, as shown above.




回答2:


The real problem here is that the characters [ and ] are illegal in an HTML4 (or XML) id attribute - look at the following:

http://www.w3.org/TR/html401/types.html#type-name

(for the normative definition of the id attribute look at www.w3.org//TR/html401/struct/global.html#adef-id)




回答3:


you can also do it this way

el = doc.xpath("id(spam[500])").first

for elements having id's you can call them directly through id because its always unique.

for finding out xpaths, please add a 'xpath checker' plugin to firefox. It helps a lot and very easy



来源:https://stackoverflow.com/questions/1235774/find-tag-with-id-including-with-nokogiri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!