Home Backend Development PHP Tutorial Development case of implementing simple crawler in PHP

Development case of implementing simple crawler in PHP

Mar 21, 2018 am 11:08 AM
php develop Case

Sometimes because of work and our own needs, we will browse different websites to obtain the data we need, so crawlers come into being. The following is my process of developing a simple crawler and the problems I encountered.

To develop a crawler, you must first know what your crawler is going to be used for. I want to use it to find articles with specific keywords on different websites and get their links so that I can read them quickly.

According to personal habits, I first need to write an interface and clarify my ideas.

1. Go to different websites. Then we need a url input box.
2. Find articles with specific keywords. Then we need an article title input box.
3. Get the article link. Then we need a display container for search results.


<p class="jumbotron" id="mainJumbotron">
 <p class="panel panel-default">
 
  <p class="panel-heading">文章URL抓取</p>
 
  <p class="panel-body">
   <p class="form-group">
    <label for="article_title">文章标题</label>
    <input type="text" class="form-control" id="article_title" placeholder="文章标题">
   </p>
   <p class="form-group">
    <label for="website_url">网站URL</label>
    <input type="text" class="form-control" id="website_url" placeholder="网站URL">
   </p>
 
   <button type="submit" class="btn btn-default">抓取</button>
  </p>
 </p>
 <p class="panel panel-default">
 
  <p class="panel-heading">文章URL</p>
 
  <p class="panel-body">
   <h3></h3>
  </p>
 </p>
</p>
Copy after login

Add the code directly, and then add some style adjustments of your own, and the interface is complete:

Then The next step is to implement the function. I use PHP to write it. The first step is to obtain the html code of the website. There are many ways to obtain the html code. I will not introduce them one by one. Here I use curl to obtain and pass in You can get the html code from the website url:


private function get_html($url){
 
 $ch = curl_init();
 
 $timeout = 10;
 
 curl_setopt($ch, CURLOPT_URL, $url);
 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
 curl_setopt($ch, CURLOPT_ENCODING, &#39;gzip&#39;);
 
 curl_setopt($ch, CURLOPT_USERAGENT, &#39;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36&#39;);
 
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 
 $html = curl_exec($ch);
 
 return $html;
 
}
Copy after login

Although you get the html code, you will soon encounter a problem, that is, the encoding problem, which may make you The next step of matching is in vain. Here we uniformly convert the obtained html content to utf8 encoding:


$coding = mb_detect_encoding($html);
if ($coding != "UTF-8" || !mb_check_encoding($html, "UTF-8"))
$html = mb_convert_encoding($html, &#39;utf-8&#39;, &#39;GBK,UTF-8,ASCII&#39;);
Copy after login

得到网站的html,要获取文章的url,那么下一步就是要匹配该网页下的所有a标签,需要用到正则表达式,经过多次测试,最终得到一个比较靠谱的正则表达式,不管a标签下结构多复杂,只要是a标签的都不放过:(最关键的一步)


$pattern = &#39;|<a[^>]*>(.*)</a>|isU&#39;;
preg_match_all($pattern, $html, $matches);
Copy after login

匹配的结果在$matches中,它大概是这样的一个多维素组:


array(2) { 
 [0]=> 
 array(*) { 
  [0]=>
  string(*) "完整的a标签"
  .
  .
  .
 }
 [1]=>
 array(*) {
  [0]=>
  string(*) "与上面下标相对应的a标签中的内容"
 }
}
Copy after login

只要能得到这个数据,其他就完全可以操作啦,你可以遍历这个素组,找到你想要a标签,然后获取a标签相应的属性,想怎么操作就怎么操作啦,下面推荐一个类,让你更方便操作a标签:


$dom = new DOMDocument();
 
@$dom->loadHTML($a);//$a是上面得到的一些a标签
 
$url = new DOMXPath($dom);
 
$hrefs = $url->evaluate(&#39;//a&#39;);
 
for ($i = 0; $i < $hrefs->length; $i++) {
 
 $href = $hrefs->item($i);
 
 $url = $href->getAttribute(&#39;href&#39;); //这里获取a标签的href属性
 
}
Copy after login

当然,这只是一种方式,你也可以通过正则表达式匹配你想要的信息,把数据玩出新花样。

得到并匹配得出你想要的结果,下一步当然就是传回前端将他们显示出来啦,把接口写好,然后前端用js获取数据,用jquery动态添加内容显示出来:


var website_url = &#39;你的接口地址&#39;;
$.getJSON(website_url,function(data){
 if(data){
  if(data.text == &#39;&#39;){
   $(&#39;#article_url&#39;).html(&#39;<p><p>暂无该文章链接</p></p>&#39;);
   return;
  }
  var string = &#39;&#39;;
  var list = data.text;
  for (var j in list) {
    var content = list[j].url_content;
    for (var i in content) {
     if (content[i].title != &#39;&#39;) {
      string += &#39;<p class="item">&#39; +
       &#39;<em>[<a href="http://&#39; + list[j].website.web_url + &#39;" target="_blank">&#39; + list[j].website.web_name + &#39;</a>]</em>&#39; +
       &#39;<a href=" &#39; + content[i].url + &#39;" target="_blank" class="web_url">&#39; + content[i].title + &#39;</a>&#39; +
       &#39;</p>&#39;;
     }
    }
   }
  $(&#39;#article_url&#39;).html(string);
});
Copy after login

上最终效果图:

The above is the detailed content of Development case of implementing simple crawler in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles