【问题标题】:DOM. Get value attribute from a given text in option tagDOM。从选项标签中的给定文本中获取值属性
【发布时间】:2015-05-27 15:08:35
【问题描述】:

我正在尝试通过 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 作为参数传递,而是传递文本。

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

【问题讨论】:

    标签: php dom xpath css-selectors goutte


    【解决方案1】:

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

    【讨论】:

    • 你的意思是字符串作为一个 PHP 函数,它接收 xpath //option[.="7-Zip"]/@value 作为参数¿?
    【解决方案2】:

    参考文献:

    1. Symfony DomCrawler Component Documentation - Accessing DomCrawler Node Values
    2. DomCrawler API Reference - filterXPath() Method
    3. DomCrawler API Reference - extract() method
    4. Github Code View - 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
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2012-10-02
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      相关资源
      最近更新 更多