1

我正在尝试通过 CSS 选择器或 xpath 表达式从给定文本中获取值,但我不知道是否可以执行此操作。这是我的 HTML:

 <select name="product" style="width: 430px">
<option value="0" selected="selected"></option>
<option value="3181">389-ds-base</option>
<option value="3511">7-Zip</option>

假设我想通过给出文本来获得值 3511。

我想要这个的原因是因为我想做这样的网络爬行:

require_once '/root/PHP/goutte.phar';

use Goutte\Client;

$client = new Client();

$crawler = $client->request('GET', 'https://oval.mitre.org/repository/data/search/');
$form = $crawler->selectButton('Search')->form();
$crawler = $client->submit($form, array('product' => '3511'));
$nodeValues = $crawler->filterXPath('//td[@nowrap][position()>4]/a')->each(function ($node) {
    return $node->text();
});

而且我不想将数字 3511 作为参数传递,而是传递文本。

希望我说清楚了,提前谢谢你。

4

2 回答 2

3

参考:

  1. Symfony DomCrawler 组件文档 - 访问 DomCrawler 节点值
  2. DomCrawler API 参考 - filterXPath() 方法
  3. DomCrawler API 参考 - extract() 方法
  4. Github 代码查看 - DomCrawler::filter()
  5. DOMXPath::query()

首先,我想请您注意 DomCrawler::filter() 和 DomCrawler::filterXPath() 方法是 DomCrawler::filterRelativeXPath() 私有方法的包装器。

浏览一下 filter() 和 filterXPath() 方法的 API 参考,您会注意到它们都将返回一个 DomCrawler 实例;从 filterRelativeXPath() 方法中可以看到。filterRelativeXPath() 方法又使用 PHP 的 XPath::query() 方法。

Paul 提供的 XPath 表达式虽然在技术上是正确的,但不适用于 Symfony DomCrawler 的上下文。事实上,如果你这样做:

$value = $crawler->filterXPath('string(//option[.="7-Zip"]/@value)');

您可能会从 DOMXPath::query() 收到错误或警告

使用 Symfony DomCrawler 组件时,您必须执行以下操作:

$value = $crawler->filterXPath('//option[.="7-Zip"]/') // get the node
                 ->extract(['value'])[0];              // extract the value attribute and then associate the first element of the resulting array to $value
于 2015-03-31T23:17:21.407 回答
1

xpath 表达式string(//option[.="7-Zip"]/@value)将查找<option>文本内容等于“7-Zip”的任何元素,并将其value属性作为字符串返回。

于 2015-03-24T10:45:30.787 回答