search
HomeBackend DevelopmentPHP Tutorialphp implements the development of simple crawlers, php implements crawlers_PHP tutorial

PHP implements the development of simple crawlers, PHP implements crawlers

Sometimes because of work and our own needs, we will browse different websites to obtain the data we need, so crawlers should be used Now, the following is my process and problems encountered in developing a simple crawler.

To develop a crawler, first you need to 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.

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

Add the code directly, 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. Curl is used here. Get, pass in the website url and you will get the html code:

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, 'gzip');
 
 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');
 
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 
 $html = curl_exec($ch);
 
 return $html;
 
}

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

$coding = mb_detect_encoding($html);
if ($coding != "UTF-8" || !mb_check_encoding($html, "UTF-8"))
$html = mb_convert_encoding($html, 'utf-8', 'GBK,UTF-8,ASCII');

Get the html of the website and get the url of the article. Then the next step is to match all a tags under the web page. You need to use regular expressions. After many tests, you finally get a more reliable regular expression. , no matter how complex the structure under the a tag is, as long as it is a tag, it will not be missed: (the most critical step)

$pattern = '|<a[^>]*>(.*)</a>|isU';
preg_match_all($pattern, $html, $matches);

The matching result is in $matches, which is probably a multi-dimensional group like this:

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

As long as you can get this data, everything else is completely operable. You can traverse this element group, find the a tag you want, and then get the corresponding attributes of the a tag. You can do whatever you want. Here is a class recommended , making it easier for you to operate a tag:

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

Of course, this is just one way. You can also use regular expressions to match the information you want and play new tricks with the data.

Get and match the results you want. The next step is of course to send them back to the front end to display them. Write the interface, then use js to get the data on the front end, and use jquery to dynamically add the content and display it:

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

The final rendering:

Articles you may be interested in:

  • php IIS log analysis search engine crawler recording program
  • php displays different content to visitors and crawlers
  • a A lightweight simple crawler implemented in PHP
  • How to implement a simple crawler in PHP
  • PHP code to implement crawler records - super useful
  • Millions of PHP crawler Zhihu users Data crawling and analysis
  • PHP HTML JavaScript Css to implement simple crawler development

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1117098.htmlTechArticleDevelopment of simple crawlers in php. Implementation of crawlers in php. Sometimes because of work and our own needs, we will browse different website to obtain the data we need, so crawlers came into being,...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment