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 相关文章推荐
pdo中使用参数化查询sql
Aug 11 PHP
如何给phpcms v9增加类似于phpcms 2008中的关键词表
Jul 01 PHP
一个PHP二维数组排序的函数分享
Jan 17 PHP
PHP加密解密类实例分析
Apr 20 PHP
Cygwin中安装PHP方法步骤
Jul 04 PHP
学习php设计模式 php实现享元模式(flyweight)
Dec 07 PHP
详解WordPress中用于合成数组的wp_parse_args()函数
Dec 18 PHP
PHP超低内存遍历目录文件和读取超大文件的方法
May 01 PHP
tp5(thinkPHP5框架)captcha验证码配置及验证操作示例
May 28 PHP
PHP实现提高SESSION响应速度的几种方法详解
Aug 09 PHP
PHP全局使用Laravel辅助函数dd
Dec 26 PHP
PHP sdk实现在线打包代码示例
Dec 09 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中mysql与mysqli的区别分析
2013/06/10 PHP
PHP生成Gif图片验证码
2013/10/27 PHP
php缩放gif和png图透明背景变成黑色的解决方法
2014/10/14 PHP
php读取文件内容的方法汇总
2015/01/24 PHP
yii2实现根据时间搜索的方法
2016/05/25 PHP
PHP入门教程之图像处理技巧分析
2016/09/11 PHP
在textarea中显示html页面的javascript代码
2007/04/20 Javascript
jquery 查找select ,并触发事件的实现代码
2011/03/30 Javascript
离开当前页面前使用js判断条件提示是否要离开页面
2014/05/02 Javascript
JavaScript学习笔记之JS函数
2015/01/22 Javascript
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
js判断图片加载完成后获取图片实际宽高的方法
2016/02/25 Javascript
JavaScript程序中的流程控制语句用法总结
2016/05/23 Javascript
jQuery实现一个简单的验证码功能
2017/06/26 jQuery
基于Vue实例对象的数据选项
2017/08/09 Javascript
微信小程序switch组件使用详解
2018/01/31 Javascript
webpack自动打包和热更新的实现方法
2019/06/24 Javascript
node.js使用zlib模块进行数据压缩和解压操作示例
2020/02/12 Javascript
Python守护线程用法实例
2017/06/23 Python
pygame 精灵的行走及二段跳的实现方法(必看篇)
2017/07/10 Python
利用Pandas 创建空的DataFrame方法
2018/04/08 Python
基于Django URL传参 FORM表单传数据 get post的用法实例
2018/05/28 Python
python 构造三维全零数组的方法
2018/11/12 Python
Python嵌套函数,作用域与偏函数用法实例分析
2019/12/26 Python
基于python实现上传文件到OSS代码实例
2020/05/09 Python
Python使用正则表达式实现爬虫数据抽取
2020/08/17 Python
Python Merge函数原理及用法解析
2020/09/16 Python
python软件测试Jmeter性能测试JDBC Request(结合数据库)的使用详解
2021/01/26 Python
台湾饭店和机票预订网站:Expedia台湾
2016/08/05 全球购物
伦敦剧院及景点门票:Encore Tickets
2018/07/01 全球购物
物业管理计划书
2014/01/10 职场文书
市场开发与营销专业求职信范文
2014/05/01 职场文书
会议欢迎词范文
2015/01/27 职场文书
语文教师个人工作总结
2015/02/06 职场文书
学生犯错保证书
2015/05/09 职场文书
Python实现日志实时监测的示例详解
2022/04/06 Python