phpquery中文手册


Posted in PHP onMarch 18, 2021

【简介】

phpQuery是一个基于PHP的服务端开源项目,它可以让PHP开发人员轻松处理DOM文档内容。更有意思的是,它采用了jQuery的思想,使得可以像使用jQuery一样处理页面内容,获取想要的页面信息。

【步骤】

1.引入phpquery类库

include 'phpQuery/phpQuery.php'; 

2加载需要获取内容的网页连接或则文档

加载文档主要通过phpQuery::newDocument()来进行操作,其作用是使得phpQuery可以在服务器预先读取到指定的文件或文本内容。

主要的常用方法包括:
phpQuery::newDocumentFile($file,$contentType = null)
$file可以是一个网址地址(带http的)或则html文件路径,如果 $contentType为空,则根据文档自动检测编码。检测失败,则对于text/html类型文档自动赋予utf-8编码。

phpQuery::newDocument($html)

$html是html格式的字符串或则代码;

<?php
header("Content-Type: text/html;charset=utf-8"); 
require('phpQuery/phpQuery.php');
/*通过读取URL或则文件路径 返回值是该网站或文件的html,一个网页对应着一个html文件*/
/*eg 1*/
$eg1=phpQuery::newDocumentFile("test.htm");

/*eg 2*/
 $eg2=phpQuery::newDocumentFile("http://www.baidu.com");

//可以通过echo htmlentities($eg1,ENT_QUOTES,"UTF-8");查看返回值。注意htmlentities()函数可以输出原始html代码。

/*eg 3*/
//读入html
$html="<div>
        <ul>
            <li>第一行</li>
            <li>第二行</li>
        </ul>
       </div";
$eg3=phpQuery::newDocument($html);//输入入参数为html


?>

phpQuery::newDocument($file)初始加载时返回html的串后,就可以使用html操作句柄函数——pq(),通过pq()来筛选提取指定的内容。

3 pq()函数用法
pq($param, $context = null);
pq()函数的用法是phpQuery的重点,pq($xpath,$DocumentID)函数有个参数,第一个$xpath是通过html标签/类/id等定位到某一元素,$DocumentID可以看做为一个指针,指向需要查询的html文档(也就是phpQuery::newDocumentFile($file)的返回结果,如:$eg1或$eg2或$eg3——其实也就是html的context)。当同时对多个文档操作时,需要用到这个参数,如果没有给出,会自动邻近匹配匹配,因此如果只对一个文档操作时,可以省略即使用——pq($xpath)就可以。
pq(); 相当于 jQuery的$();。

主要分两部分:即选择器和过滤器

4 选择器

【基本选择器】

  • #id 根据给定的ID属性匹配单个元素。
  • element 根据给定的名称匹配所有符合的元素。
  • .class 根据给定的class匹配所有的元素。
  • * 选择所有元素。
  • selector1, selector2, selectorN 根据所有制定的选择器匹配结合结果 选择结果是取并集
/* 基本选择器*/
#id                     pq("#myDiv");
element                 pq("div"); 
.class                  pq(".myClass"); 
*                       pq("*") 
selector1,selectorN     pq("div,span,p.myClass")

【层次选择器】

  • ancestor descendant 匹配由先祖指定的元素的后代指定的所有后代元素。
  • parent > child 匹配由父元素指定的子元素指定的所有子元素。
  • prev + next 根据指定的”next”和指定的”prev”匹配所有的下一个元素。
  • prev ~ siblings 匹配根据”prev” 元素的 所有相邻元素。
/* 层次选择器*/
ancestor descendant     pq("form input") 
parent > child          pq("form > input") 
prev + next             pq("label + input") 
prev ~ siblings         pq("form ~ input")

5 过滤器

【基础过滤 】

  • :first 匹配第一个被选择的元素。
  • :last 匹配最后一个被选择的元素。
  • :not(selector) 匹配所有不是被选择的元素。
  • :even 匹配所有被选择的偶数元素,0索引。
  • :odd 匹配所有被选择的奇数元素,0索引。
  • :eq(index) 匹配等同于给定的索引的元素。
  • :gt(index) 匹配大于给定的索引的元素。
  • :lt(index) 匹配小于给定的索引的元素。
  • :header 匹配所有header元素,如h1,h2,h3等。
  • :animated 匹配正在进行动画效果的元素。
/*基础过滤*/
:first                  pq("tr:first") 
:last                   pq("tr:last") 
:not(selector)          pq("input:not(:checked)") 
:even                   pq("tr:even") 
:odd                    pq("tr:odd") 
:eq(index)              pq("tr:eq(1)")
:gt(index)              pq("tr:gt(0)") 
:lt(index)              pq("tr:lt(2)")
:header                 pq(":header").css("background", "#EEE");

【内容过滤】

  • :contains(text) 匹配包含指定文本的元素。
  • :empty 匹配所有无子节点的元素(包括文本节点)。
  • :has(selector) 匹配至少包含一个对于给定选择器的元素。
  • :parent 匹配所有父元素 - 拥有子元素的,包括文本。
/*内容过滤*/
:contains(text)         pq("div:contains('John')") 
:empty                  pq("td:empty") 
:has(selector)          pq("div:has(p)").addClass("test"); 
:parent                 pq("td:parent")

【属性过滤】

  • [attribute] 匹配给定属性的元素。
  • [attribute=value] 匹配给定属性等于确定值的元素。
  • [attribute!=value] 匹配给定属性不等于确定值的元素。
  • [attribute^=value] 匹配给定属性是确定值开始的元素。
  • [attribute$=value] 匹配给定属性是确定值结尾的元素。
  • [attribute*=value] 匹配给定属性包含确定值的元素。
  • [selector1selector2selectorN] 匹配给定属性并且包含确定值的元素。
[attribute]             pq("div[id]") 
[attribute=value]       pq("input[name='newsletter']").attr("checked", true); 
[attribute!=value]      pq("input[name!='newsletter']").attr("checked", true); 
[attribute^=value]      pq("input[name^='news']")
[attribute$=value]      pq("input[name$='letter']")
[attribute*=value]      pq("input[name*='man']")
[selector1][selectorN]  pq("input[id][name$='man']")

【子元素过滤 】

  • :nth-child(index/even/odd/equation) 匹配所有是父元素的第n个的子元素,或者是父元素的偶数或者奇数子元素。
  • :first-child 匹配所有是父元素的第一个的子元素。
  • :last-child 匹配所有是父元素的最后一个的子元素。
  • :only-child 匹配所有是父元素唯一子元素的子元素。
:nth-child(index/even/odd/equation) pq("ul li:nth-child(2)")
:first-child                        pq("ul li:first-child")
:last-child                         pq("ul li:last-child")
:only-child                         pq("ul li:only-child")

【基于表单 】

  • :input 匹配input, textarea, select和button元素。
  • :text 匹配所有类型为text的input元素。
  • :password 匹配所有类型为password的input元素。
  • :radio 匹配所有类型为radio的input元素。
  • :checkbox 匹配所有类型为checkbox的input元素。
  • :submit 匹配所有类型为submit的input元素。
  • :image 匹配所有类型为image的input元素。
  • :reset 匹配所有类型为reset的input元素。
  • :button 匹配所有类型为button的input元素和button元素。
  • :file 匹配所有类型为file的input元素。
  • :hidden 匹配所有类型为hidden的input元素或者其他hidden元素。
:input                  pq(":input")
:text                   pq(":text")
:password               pq(":password")
:radio                  pq(":radio")
:checkbox               pq(":checkbox")
:submit                 pq(":submit")
:image                  pq(":image")
:reset                  pq(":reset") 
:button                 pq(":button")
:file                   pq(":file")
:hidden                 pq("tr:hidden")

【表单过滤 】

  • :enabled 匹配所有可用元素。
  • :disabled 匹配所有不可用元素。
  • :checked 匹配所有被勾选的元素。
  • :selected 匹配所有被选择的元素。
:enabled                pq("input:enabled")
:disabled               pq("input:disabled")
:checked                pq("input:checked")
:selected               pq("select option:selected")

【attr属性获取】

  • attr($name) 访问第一个给名称的元素的属性。这个方法可以很轻易地取得第一个匹配到的元素的属性值。如果这个元素没有对应名称的属性则返回undefined。
  • attr($properties) 对于所有匹配到的元素设置对应属性。
  • attr($key, $value) 对于匹配到的元素设置一个属性和对应值。
  • attr($key, $fn) 对于匹配到的元素设置一个属性和需要计算的值。
  • removeAttr($name) 对匹配到的元素移除给定名称的属性。
  • addClass($class) 对匹配到的元素添加一个给定的类。
  • hasClass($class) 如果有至少一个匹配到的元素包含给定的类则返回true。
  • removeClass($class) 对匹配到的元素移除给定名称的类。
  • toggleClass($class) 对匹配到的元素,如果类不存在则添加,如果存在则移除。
attr                    pq("img")->attr("src");
attr(properties)        pq("img")->attr({ src: "test.jpg", alt: "Test Image" });
attr(key,value)         pq("img")->attr("src","test.jpg");
attr(key,fn)            pq("img")->attr("title", function() { return this.src });
removeAttr(name)        pq("img")->removeAttr("src");
addClass(class)         pq("p")->addClass("selected");
removeClass(class)      pq("p")->removeClass("selected");
toggleClass(class)      pq("p")->toggleClass("selected");

【HTML获取】

  • html() 获取第一个匹配到的元素的html内容(innerHTML)。这个方法不适用于XML文本(但适用于XHTML。)
  • html($val) 对匹配到的元素设置html内容。这个方法不适用于XML文本(但适用于XHTML。)
1) html()                  pq("div")->html();
2) html(val)               pq("div")->html("<p>Hello Again</p>");

【text获取】

  • text() 获取匹配到的所有元素的文本内容。
  • text($val) 对匹配到的所有元素设置文本内容。
text()                  pq("p")->text();
text(val)               pq("p")->text("<b>Some</b> new text.");

【Value 获取】

  • val() 获取匹配到的第一个元素的value属性的值。
  • val($val) 对匹配到的元素设置value值。val($val) 所有的Checks, selects, radio buttons, checkboxes,和select options都会设置相应给定的值。
val()                   pq("input")->val();
val(val)                pq("input")->val("hello world!");

【其他筛选和文档处理】

\*筛选*\
eq(index)               pq("p")->eq(1)
hasClass(class)         pq("div")->hasClass("protected")
filter(expr)            pq("p")->filter(".selected") 
filter(fn)              pq("p")->filter(function($index) {
                              return pq("ol", pq($index))->size() == 0;
                            }); 
is(expr)                pq("input[type='checkbox']")->parent()->is("form")
map(callback)           pq("p")->append(pq("input").map(function(){
                              return pq(this)->val();
                            })->get()->join(", "));
not(expr)               pq("p")->not(pq("#selected")[0])
slice(start,[end])      pq("p")->slice(0, 1)->wrapInner("<b></b>");
add(expr)               pq("p")->add("span")
children([expr])        pq("div")->children()
contents()              pq("p")->contents()->not("[@nodeType=1]").wrap("<b/>");
find(expr)              pq("p")->find("span")
next([expr])            pq("p")->next()
nextAll([expr])         pq("div:first")->nextAll()->addClass("after");
parent([expr])          pq("p")->parent()
parents([expr])         pq("span")->parents()
prev([expr])            pq("p").prev()
prevAll([expr])         pq("div:last")->prevAll()->addClass("before"); 
siblings([expr])        pq("div")->siblings()
andSelf()               pq("div")->find("p")->andSelf()->addClass("border");
end()                   pq("p")->find("span")->end()

\*文档处理*\
append(content)         pq("p")->append("<b>Hello</b>");
appendTo(content)       pq("p")->appendTo("#foo");
prepend(content)        pq("p")->prepend("<b>Hello</b>");
prependTo(content)      pq("p")->prependTo("#foo");
after(content)          pq("p")->after("<b>Hello</b>");
before(content)         pq("p")->before("<b>Hello</b>");
insertAfter(content)    pq("p")->insertAfter("#foo");
insertBefore(content)   pq("p")->insertBefore("#foo");
wrap(html)              pq("p")->wrap("<div class='wrap'></div>");
wrap(elem)              pq("p")->wrap(pq("#content"));
wrapAll(html)           pq("p")->wrapAll("<div></div>");
wrapAll(elem)           pq("p")->wrapAll(pq("#content")); 
wrapInner(html)         pq("p")->wrapInner("<b></b>");
wrapInner(elem)         pq("p")->wrapInner(pq(".content"));
replaceWith(content)    pq("p")->replaceWith("<b>Paragraph. </b>");
replaceAll(selector)    pq("<b>Paragraph. </b>")->replaceAll("p");
empty()                 pq("p")->empty();
remove([expr])          pq("p")->remove();
clone()                 pq("b")->clone()->prependTo("p");
clone(true)             pq("button")->clone(true)->insertAfter(pq("b"))

 

[测试 爬取简单示例]


以武汉大学通知公告http://www.whu.edu.cn/tzgg.htm为例进行爬取测试test.php

<?php
header("Content-Type: text/html;charset=utf-8"); 
require('phpQuery/phpQuery.php');
$eg1=phpQuery::newDocumentFile("http://www.whu.edu.cn/tzgg.htm");
$eg2=phpQuery::newDocumentFile("https://www.baidu.com/");

echo pq("title",$eg1)->html()."<br>";
echo pq("title",$eg1->getDocumentID())->html()."<br>";//$eg1$eg1->getDocumentID()效果等同
echo pq("title")->html()."<br>";//就近匹配 $eg2

phpQuery::selectDocument($eg1); //默认会使用选定的文档
echo pq("title")->html()."<br>";


// $mes=pq("ul")->html();//获取所有的ul标签中的html内容
// echo $mes;
// echo "<br>___________________<br>";
// $mes=pq("ul,li")->html();//获取所有的ul以及li标签中的html内容
// echo $mes;

// $t=pq("ul[class='article']")->html();//获取ul class="article"的html内容
// echo $t;


$t=pq("ul[class='article']>li:eq(2)")->html();//获取ul class="article" 下第二个子元素li的html内容
echo $t;
$t=pq("ul[class='article']>li:eq(2)>center>div:eq(1)")->html();
echo $t."<br>";

$t=pq("(ul[class='article']>li:eq(2)>center>div:eq(1))")->html();
echo $t."<br>";
$t=pq("(ul[class='article']>li:eq(3)>div[class='col-xs-12 col-sm-6 col-md-6']>a")->html();
echo $t."<br>";

$t=pq("(ul[class='article']>li:eq(3)>div[class='col-xs-12 col-sm-6 col-md-6']>a")->attr("href");
echo $t."<br>";

?>
PHP 相关文章推荐
PHP制作图型计数器的例子
Oct 09 PHP
php中目录,文件操作详谈
Mar 19 PHP
php数组函数序列之array_flip() 将数组键名与值对调
Nov 07 PHP
smarty内置函数section的用法
Jan 22 PHP
php项目中百度 UEditor 简单安装调试和调用
Jul 15 PHP
Java中final关键字详解
Aug 10 PHP
zend framework中使用memcache的方法
Mar 04 PHP
Zend Framework实现将session存储在memcache中的方法
Mar 22 PHP
PHP面向对象自动加载机制原理与用法分析
Oct 14 PHP
在云虚拟主机部署thinkphp5项目的步骤详解
Dec 21 PHP
浅析PHP数据导出知识点
Feb 17 PHP
Laravel5.7 数据库操作迁移的实现方法
Apr 12 PHP
thinkphp5 路由分发原理
Mar 18 #PHP
is_file和file_exists效率比较
Mar 14 #PHP
宝塔面板出现“open_basedir restriction in effect. ”的解决方法
open_basedir restriction in effect. 原因与解决方法
Mar 14 #PHP
aec加密 php_php aes加密解密类(兼容php5、php7)
Mar 14 #PHP
PHP配置文件php.ini中打开错误报告的设置方法
Jan 09 #PHP
imagettftext() 失效,不起作用
Mar 09 #PHP
You might like
二招解决php乱码问题
2012/03/25 PHP
PHP Class&amp;Object -- PHP 自排序二叉树的深入解析
2013/06/25 PHP
PHP变量的定义、可变变量、变量引用、销毁方法
2013/12/20 PHP
PHP中copy on write写时复制机制介绍
2014/05/13 PHP
常用PHP封装分页工具类
2017/01/14 PHP
解决PHPstudy Apache无法启动的问题【亲测有效】
2020/10/30 PHP
SinaEditor使用方法详解
2013/12/28 Javascript
js获取元素外链样式的方法
2015/01/27 Javascript
JS实现动态给图片添加边框的方法
2015/04/01 Javascript
jQuery实现多级下拉菜单jDropMenu的方法
2015/08/28 Javascript
jQuery数据类型小结(14个)
2016/01/08 Javascript
学习使用bootstrap基本控件(table、form、button)
2016/04/12 Javascript
JS继承之借用构造函数继承和组合继承
2016/09/07 Javascript
bootstrap 路径导航 分页 进度条的实例代码
2018/08/06 Javascript
微信小程序如何利用getCurrentPages进行页面传值
2019/07/01 Javascript
移动端手指操控左右滑动的菜单
2019/09/08 Javascript
js判断鼠标移入移出方向的方法
2020/06/24 Javascript
JS删除对象中某一属性案例详解
2020/09/08 Javascript
layui使用及简单的三级联动实现教程
2020/12/01 Javascript
python爬虫常用的模块分析
2014/08/29 Python
python的re模块应用实例
2014/09/26 Python
Python中实现结构相似的函数调用方法
2015/03/10 Python
Python基于有道实现英汉字典功能
2015/07/25 Python
简单理解Python中的装饰器
2015/07/31 Python
运动检测ViBe算法python实现代码
2018/01/09 Python
在python中利用最小二乘拟合二次抛物线函数的方法
2018/12/29 Python
python调用HEG工具批量处理MODIS数据的方法及注意事项
2020/02/18 Python
Django models filter筛选条件详解
2020/03/16 Python
彻底搞懂python 迭代器和生成器
2020/09/07 Python
html5如何及时更新缓存文件(js、css或图片)
2013/06/24 HTML / CSS
微信html5页面调用第三方位置导航的示例
2018/03/14 HTML / CSS
2014学校庆三八妇女节活动总结
2014/03/01 职场文书
人力资源管理系自荐信
2014/05/31 职场文书
企业廉洁教育心得体会
2016/01/20 职场文书
Mysql中 unique列插入重复值该怎么解决呢
2021/05/26 MySQL
pytorch 运行一段时间后出现GPU OOM的问题
2021/06/02 Python