这篇文章首发在吹水小镇:http://blog.reetsee.com/archives/366
要在手机或者电脑看到更好的图片或代码欢迎到博文原地址。也欢迎到博文原地址批评指正。
??????????????????????????????
export LANG=en_US.UTF-8????????????????????????????????
0 背景
背景是这样的目前 吹水新闻( http://news.reetsee.com)下的内容全部由Python的爬虫抓取,使用的框架是Python的 Scrapy,而吹水新闻目前是运行在 BAE(百度应用引擎)下的,每个月还需要交钱。目前我的想法是把吹水新闻完全迁移到目前这台阿里云主机上,并且原本的新闻我每天都手动执行一次脚本来抓取再更新到网站,等迁移到这里后就能直接使用Crontab定时脚本自动更新新闻了!最近工作都在用 PHP,开发网站的新页面要PHP,直接读写数据库也能用PHP,那么就直接用PHP重构新闻网站好了。准备开干的时候却发现没找到一个好的PHP爬虫框架(可能是我没仔细找),于是就打算自己写一个,因此就有了这个Phpfetcher。名字起得略好……但是代码写得略搓……不管怎么样,目前基本可以用,而且应该能满足不少简单的需求,下面就是使用示例。1 基本概念
在Phpfetcher中有四个主要的对象,依次是:Dom,Page,Crawler,Manager。2 简单例子
****** 实例1:single_page.php ******例如我们要抓取这个网站的内容: http://news.qq.com/a/20140927/026557.htm里面有很多超链接,有标题,有新闻详细内容,或者其它我们关心的内容。先看一下下面的例子:<?phprequire_once('phpfetcher.php');class mycrawler extends Phpfetcher_Crawler_Default { public function handlePage($page) { //打印处当前页面的title $res = $page->sel('//title'); for ($i = 0; $i < count($res); ++$i) { echo $res[$i]->plaintext; echo "\n"; } }}$crawler = new mycrawler();$arrJobs = array( //任务的名字随便起,这里把名字叫qqnews //the key is the name of a job, here names it qqnews 'qqnews' => array( 'start_page' => 'http://news.qq.com/a/20140927/026557.htm', //起始网页 'link_rules' => array( /* * 所有在这里列出的正则规则,只要能匹配到超链接,那么那条爬虫就会爬到那条超链接 * Regex rules are listed here, the crawler will follow any hyperlinks once the regex matches */ ), //爬虫从开始页面算起,最多爬取的深度,设置为1表示只爬取起始页面 //Crawler's max following depth, 1 stands for only crawl the start page 'max_depth' => 1, ) , );//$crawler->setFetchJobs($arrJobs)->run(); 这一行的效果和下面两行的效果一样$crawler->setFetchJobs($arrJobs);$crawler->run();将这个脚本和“phpfetcher.php”以及“Phpfetcher”文件夹放在同一个目录下(或者将“phpfetcher.php”和“Phpfetcher”放到你的PHP环境默认include的查找路径),执行这个脚本,得到的输出如下:
[root@reetsee demo]# php single_page.php 王思聪回应遭警方调查:带弓箭不犯法 我是绿箭侠_新闻_腾讯网查看一下我们抓取的网页源代码,可以发现是下面这几行中的title标签内容提取出来了:
<!DOCTYPE html><html lang="zh-CN"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"></meta> <meta charset="gb2312"></meta> <title> 王思聪回应遭警方调查:带弓箭不犯法 我是绿箭侠_新闻_腾讯网 </title>上面就是一个最简单的例子。 ****** 实例2:multi_page.php ******接下来就是另外一个简单的例子,例如说腾讯新闻的主页,上面有各种新闻,我们这次的目标是把腾讯新闻主页( http://news.qq.com)显示的部分新闻标题抓下来,直接先上例程:
<?php//下面两行使得这个项目被下载下来后本文件能直接运行$demo_include_path = dirname(__FILE__) . '/../';set_include_path(get_include_path() . PATH_SEPARATOR . $demo_include_path);require_once('phpfetcher.php');class mycrawler extends Phpfetcher_Crawler_Default { public function handlePage($page) { //打印处当前页面的第1个h1标题内荣(下标从0开始) $strFirstH1 = trim($page->sel('//h1', 0)->plaintext); if (!empty($strFirstH1)) { echo $page->sel('//h1', 0)->plaintext; echo "\n"; } }}$crawler = new mycrawler();$arrJobs = array( //任务的名字随便起,这里把名字叫qqnews //the key is the name of a job, here names it qqnews 'qqnews' => array( 'start_page' => 'http://news.qq.com', //起始网页 'link_rules' => array( /* * 所有在这里列出的正则规则,只要能匹配到超链接,那么那条爬虫就会爬到那条超链接 * Regex rules are listed here, the crawler will follow any hyperlinks once the regex matches */ '#news\.qq\.com/a/\d+/\d+\.htm$#', ), //爬虫从开始页面算起,最多爬取的深度,设置为2表示爬取深度为1 //Crawler's max following depth, 1 stands for only crawl the start page 'max_depth' => 2, ) , );$crawler->setFetchJobs($arrJobs)->run(); //这一行的效果和下面两行的效果一样//$crawler->setFetchJobs($arrJobs);//$crawler->run();相比于第1个例子,变化的地方有几个:首先这次我们增加了一条爬虫跟踪的规则“#news\.qq\.com/a/\d+/\d+\.htm$#”(注:PHP使用pcre正则表达式,可以到 PHP关于正则表达式的页面看一下),这是一个正则表达式,例如这种超链接“news.qq.com/a/12345678/00234.htm”那么爬虫就会跟踪;然后是我们把爬虫的最大跟踪深度设置为2,这样爬虫会跟踪1次起始页面上符合要求的超级链接;最后是我把原本的Dom选择从“//title”改为了“//h1”,意思就是抓取h1标签的内容而不是像之前那样抓取title标签,想知道这种Dom选择器的选择规则,需要了解一下 xpath。运行这个文件,能够看到大致效果如下: 这样第二个例子就结束了。暂时我就介绍这两个例子吧,Phpfetcher的源代码在这里: https://github.com/fanfank/phpfetcher把代码下载下来后,demo内的东西就可以直接运行了(当然你需要一个有curl和mb_string扩展的php,可以使用“php -m”命令来看一下你的PHP有没有装这两个扩展)。
3 后话
实际上这个phpfetcher目前还有很多问题,性能应该是比较差的,不过毕竟也是我写的第一个框架。另外是关于phpfetcher我有很多东西还没有提到,例如Page对象的一些设置,Crawler对象的设置等,主要是目前太过懒不想写文档,也不知道有没有必要写。我感觉这个框架还是蛮简单的,里面主要的函数我都做了详细的注释,欢迎阅读批评指正给建议!最后就是,如果你想写个爬虫,又想用PHP来写,不妨试一下phpfetcher。 祝大家国庆节快乐~!
PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft