Table of Contents
PHP+HTML+JavaScript+Css实现简单爬虫开发,javascriptcss
您可能感兴趣的文章:
Home Backend Development PHP Tutorial PHP+HTML+JavaScript+Css实现简单爬虫开发,javascriptcss_PHP教程

PHP+HTML+JavaScript+Css实现简单爬虫开发,javascriptcss_PHP教程

Jul 12, 2016 am 08:55 AM
javascript php reptile

PHP+HTML+JavaScript+Css实现简单爬虫开发,javascriptcss

开发一个爬虫,首先你要知道你的这个爬虫是要用来做什么的。我是要用来去不同网站找特定关键字的文章,并获取它的链接,以便我快速阅读。

按照个人习惯,我首先要写一个界面,理清下思路。

    1、去不同网站。那么我们需要一个url输入框。

    2、找特定关键字的文章。那么我们需要一个文章标题输入框。

    3、获取文章链接。那么我们需要一个搜索结果的显示容器。

<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>
Copy after login

直接上代码,然后加上自己的一些样式调整,界面就完成啦:

那么接下来就是功能的实现了,我用PHP来写,首先第一步就是获取网站的html代码,获取html代码的方式也有很多,我就不一一介绍了,这里用了curl来获取,传入网站url就能得到html代码啦:

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;
 
}
Copy after login

虽然得到了html代码,但是很快你会遇到一个问题,那就是编码问题,这可能让你下一步的匹配无功而返,我们这里统一把得到的html内容转为utf8编码:

$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');
Copy after login

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

$pattern = '|<a[^>]*>(.*)</a>|isU';
 
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('//a');
 
for ($i = 0; $i < $hrefs->length; $i++) {
 
 $href = $hrefs->item($i);
 
 $url = $href->getAttribute('href'); //这里获取a标签的href属性
 
}
Copy after login

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

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

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);
});
Copy after login

上最终效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助。

您可能感兴趣的文章:

  • NodeJS制作爬虫全过程
  • NodeJS制作爬虫全过程(续)
  • nodejs爬虫抓取数据乱码问题总结
  • nodejs爬虫抓取数据之编码问题
  • 基于Node.js的强大爬虫 能直接发布抓取的文章哦
  • Java实现爬虫给App提供数据(Jsoup 网络爬虫)
  • Nodejs爬虫进阶教程之异步并发控制
  • node.js基础模块http、网页分析工具cherrio实现爬虫
  • Node.js编写爬虫的基本思路及抓取百度图片的实例分享
  • nodeJs爬虫获取数据简单实现代码

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1117089.htmlTechArticlePHP+HTML+JavaScript+Css实现简单爬虫开发,javascriptcss 开发一个爬虫,首先你要知道你的这个爬虫是要用来做什么的。我是要用来去不同网站找特...
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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 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
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
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.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

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.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

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's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles