【问题标题】:Select p tag after h2 that has a child with id在 h2 之后选择 p 标签,该标签有一个带有 id 的孩子
【发布时间】:2015-12-26 22:42:47
【问题描述】:

如何选择在具有特定子标签的标签之后的 p 标签?使用网络爬虫。 http://symfony.com/doc/current/components/css_selector.html

$crawler->filter('h2 span#hello + p')->each(function ($node) {
    var_dump($node->html());
});

例子:

<h2><span id="hello">Hi</span></h2>
<p>I want this p-tag, that is after the h2 above</p>
 <p>me too!</p>
<a>Not me!</a>
<h2>lol</h2>
<p>yo, not me</p>

不起作用。

【问题讨论】:

  • 这是一个相当定制的屏幕抓取。您必须使用 symfony2 还是只编写自己的 PHP 代码?
  • 没关系,我只需要那个信息。
  • 我更新了,澄清它是 h2 之后的所有 p 标签,直到出现另一个标签。
  • 我已更新答案以反映已更改的问题! :-)

标签: php symfony


【解决方案1】:

通常最好使用 DOMDocument 类 (http://php.net/manual/en/class.domdocument.php) 遍历 HTML,但您也可以使用正则表达式:

// put the example HTML code into a string
$html = <<< EOF
<h2><span id="hello">Hi</span></h2>
<p>I want this p-tag, that is after the h2 above</p>
 <p>me too!</p>
<a>Not me!</a>
<h2>lol</h2>
<p>yo, not me</p>
EOF;

// set up a regular expression
$re = "/<h2[^>]*>.*?<span[^>]*id=\"hello\"[^>]*>.*?<\\/h2[^>]*>.*?(<p.*?)<[^\\/p]/sim";
// get the match ... the (.*?) in the above regex
preg_match($re,$html,$matches);

print $matches[1];

会输出:

&lt;p&gt;I want this p-tag, that is after the h2 above&lt;p&gt;

&lt;p&gt;me too!&lt;/p&gt;

【讨论】:

  • 有 DOMDocument 的例子吗?
  • 在这种情况下,这有点棘手(至少对我来说!),这就是我建议使用正则表达式的原因。
猜你喜欢
  • 2016-10-02
  • 2020-10-29
  • 2017-12-25
  • 2019-11-08
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多