【问题标题】:How to query a dynamic classname using XPath如何使用 XPath 查询动态类名
【发布时间】:2017-04-08 03:04:23
【问题描述】:

以下是从元素中提取单个值的工作代码(基本上是获取当前汇率值。

$target_url = file_get_contents('http://www.bsp.gov.ph/statistics/sdds/exchrate.htm');
$new_dom_doc = new DOMDocument();
libxml_use_internal_errors(TRUE); //disable libxml errors
if(!empty($target_url)){ //check if target_url is actually returned
    $new_dom_doc->loadHTML($target_url);
    libxml_clear_errors(); //remove errors from yucky target_url    
    $xpath = new DOMXPath($new_dom_doc);
    echo $xpath->query('//td[@class="xl1257110"]')->item(0)->nodeValue;        
}

它工作正常,但唯一的问题是类名 //td[@class="xl1257110"] 不是静态的,因此只要类名在随机时间段后更改为随机值,代码就会中断。

有什么办法可以绕过这个问题吗?

【问题讨论】:

  • 你能给我举个例子,它不适合哪个类吗?
  • 好像已经变了。你能告诉我你到底需要哪个速率,因为我现在看不到 xl1257110 类的元素 :)

标签: php xpath web-scraping domdocument


【解决方案1】:

好吧,使用另一个标记。例如 SYMBOL 文本及其后面的表格单元格的位置。

$document = new DOMDocument();
$document->loadHTML($html);
$xpath = new DOMXpath($document);

$expression = "string(//td[text() = 'IDR']/following-sibling::td[2])";

var_dump(
  $xpath->evaluate($expression)
);

输出:

string(8) "0.000068"

//td[text() = 'IDR'] 将获取包含文本内容IDR 的表格单元格。 following-sibling:: 选择以下具有相同父节点的节点,因此 following-sibling::td 是以下 td 节点。 [2] 是一个位置(它们以 1 开头)。

string() 将结果列表中的第一个节点转换为字符串。您将得到一个空列表的空字符串。这仅适用于DOMXpath::evaluate(),不适用于DOMXpath::query()

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多