找到你要的答案

Q:Get inner text of nearest parent a tag

Q:获取最近父标签的内部文本

I'm using Ruby & Nokogiri to parse html on a page.

<div><a href="#" title="firstTitle">text one</a></div>

  <p class="OK">some content</p>
  <p class="OK">some content</p>

<div><a href="#" title="secondTitle">text two</a></div>

  <p class="WARNING">some content</p>
  <p class="WARNING">some content</p>

<div><a href="#" title="thirdTitle">text three</a></div>

  <p class="CRITICAL">some content</p>
  <p class="CRITICAL">some content</p>

Say I want to find paragraphs with a class of WARNING, I can do that successfully with:

doc = Nokogiri::HTML(html)
warning = doc.css('p.WARNING')

But now I want to target the inner text of the nearest parent a tag, in this case it would return text two.

I've tried using .first.parent.name and previous_element among other variations but have not been successful and would appreciate some insight. Thanks!

我用红宝石&;Nokogiri解析HTML页面上。

<div><a href="#" title="firstTitle">text one</a></div>

  <p class="OK">some content</p>
  <p class="OK">some content</p>

<div><a href="#" title="secondTitle">text two</a></div>

  <p class="WARNING">some content</p>
  <p class="WARNING">some content</p>

<div><a href="#" title="thirdTitle">text three</a></div>

  <p class="CRITICAL">some content</p>
  <p class="CRITICAL">some content</p>

说我想找段有警告的段落,我可以成功的用:

doc = Nokogiri::HTML(html)
warning = doc.css('p.WARNING')

但是现在我想将最近的父对象的内部文本标记为一个标签,在这种情况下它将返回文本两个。

我试着用。first.parent.name和previous_element等变化但没有成功,希望得到一些洞察。谢谢!

answer1: 回答1:

You can use XPath preceding-siblng axis to find specific sibling element before the context element. For example, given the context element is <p>, you can try something like the following to get the nearest preceding sibling div and then return the corresponding a element :

link = warning.at_xpath('./preceding-siblng::div[1]/a')

您可以使用XPath轴前siblng上下文元素之前找到具体的同辈元素。例如,给定的上下文元素是<;p>;,你可以试试下面这样的东西拿到最近的兄弟div然后返回相应的一元前:

link = warning.at_xpath('./preceding-siblng::div[1]/a')
html  css  ruby  xpath  nokogiri