php - 在 PHP 中使用 XPath 从元素中获取类
问题描述
如何使用 XPath 从此 HTML 代码中获取数字 45:
<span class="ui_bubble_rating bubble_45"></span>
这是我到目前为止所尝试的:
$rating = $xp->query('//span[@class="ui_bubble_rating"]');
$datas[$activity]['rating'] = $rating->item(0)->getAttribute('class');
请问我在这里缺少什么?
谢谢。
解决方案
我会推荐以下 XPath,正如这个问题中所建议的那样:
//span[contains(concat(" ", normalize-space(@class), " "), " ui_bubble_rating ")]
然后,您可以使用正则表达式检索您要查找的数字,该正则表达式查找前面为 的一系列数字bubble_
:
$ratingsElements = $xp->query('//span[contains(concat(" ", normalize-space(@class), " "), " ui_bubble_rating ")]');
if ($ratingsElements->length > 0) {
$firstRatingElement = $ratingsElements->item(0);
if (preg_match('/(?<=\bbubble_)\d+/', $firstRatingElement->getAttribute('class'), $matches)) {
$datas[$activity]['rating'] = $matches[0]; // 45
}
}
推荐阅读
- node.js - 房地产项目在 MongoDB 中存储数据的最佳方式
- google-apps-script - Google表格–当A列中的单元格包含字符串时删除行
- mysql - 如何删除 WITH ROLLUP 获取的不必要值并添加 TOTAL?
- html - 如何使特定元素可滚动,而不是整个页面?
- laravel - laravel 有效载荷在生产中太大
- intershop - 如何解码 BASKET 表上的 COMPUTEDITEMS 字段
- postgresql - Sqlalchemy 核心:重新格式化 select 内部的 select 查询
- javascript - 如何在单页应用程序中使用 Google adsense 广告?
- django - 根据帐户类型限制对 Django 中视图的访问
- javascript - 在里面打印对象值