search
HomeBackend DevelopmentPHP TutorialPHP爬取糗事百科主页糗事

PHP爬取糗事百科首页糗事

突然想获取一些网上的数据来玩玩,因为有SAE的MySql数据库,让它在那呆着没有什么卵用!于是就开始用PHP编写一个爬取糗事百科首页糗事的小程序,数据都保存在MySql中,岂不是很好玩!

说干就干!首先确定思路

获取HTML源码--->解析HTML--->保存到数据库

没有什么难的

1、创建PHP文件“getDataToDB.php”,

2、获取指定URL的HTML源码

这里我用的是curl函数,详细内容参见PHP手册

代码为

<span style="font-family:Times New Roman;font-size:14px;">// 获取对应链接的HTMLCODEfunction GetHtmlCode($url) {	$ch = curl_init (); // 初始化一个cur对象	curl_setopt ( $ch, CURLOPT_URL, $url ); // 设置需要抓取的网页	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // 设置crul参数,要求结果保存到字符串中还是输出到屏幕上	curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 1000 ); // 设置链接延迟	$HtmlCode = curl_exec ( $ch ); // 运行curl,请求网页	return $HtmlCode;}</span>
3、引入第三方文件’simple_html_dom.php‘来解析HTML

这里我没有能力使用正则表达式,就在网上海搜,终于找到这个,就像Java使用Jsoup(使用Jsoup解析滁州学院官网获取新闻列表)一样,具体参见BLOG

代码如下

<span style="font-family:Times New Roman;font-size:14px;">function getFmlDataToDB() {	$link = mysql_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );	// 获取源码	$html = str_get_html ( GetHtmlCode ( "http://www.qiushibaike.com/" ) );		if ($link) {		mysql_select_db ( SAE_MYSQL_DB, $link );		mysql_query ( 'set names utf8' );		// class="article block untagged mb15"		foreach ( $html->find ( 'div[class=article block untagged mb15]' ) as $per ) {						$z = null;			$t = null;			$w = null;			$d = null;			$p = null;			$ds = null;			$ps = null;						// //作者			$author = $per->find ( 'div[class=author]' );			if ($author != null) {				$a = $author [0]->find ( 'a' );				$z = $a [1]->innertext;			} else {				$z = 'no author';			}						// 头像链接						if ($author != null) {				$icon = $author [0]->find ( 'a' );				$t = $icon [0]->src->innertext;			} else {				$t = '...............';			}						// 文章内容			$content = $per->find ( 'div[class=content]' );			$w = $content [0]->innertext;						// 点赞数			$vote1 = $per->find ( 'div[class=stats]' );			$vote2 = $vote1 [0]->find ( 'span[class=stats-vote]' );			$vote3 = $vote2 [0]->find ( 'i[class=number]' );						$d = $vote3 [0]->innertext;			// 评论数			$comments1 = $vote1 [0]->find ( 'span[class=stats-comments]' );			$comments2 = $comments1 [0]->find ( 'a[class=qiushi_comments]' );			$comments3 = $comments2 [0]->find ( 'i[class=number]' );			$p = $comments3 [0]->innertext;			// 顶 数			$up_down = $per->find ( 'div[class=stats-buttons bar clearfix]' );						$up_down1 = $up_down [0]->find ( 'ul' );			$li = $up_down1 [0]->find ( 'li' );			$up = $li [0]->find ( 'span[class=number hidden]' );			$ds = $up [0]->innertext;			// 拍 数			$down = $li [1]->find ( 'span[class=number hidden]' );			$ps = $down [0]->innertext;		}	} else {		echo '数据库链接KO';	}}</span>
这个代码写的有点纠结,我试了一下不能直接获取子节点的数据,只能从外层一层一层的剥开解析,如果有新的写法,我会更新,也请各位看官看看。

4、创建数据库,将数据插入到数据库中

这里我使用的SAE中的MySQL,具体的连接方发参见使用PHP连接SAE中的MySql数据库

需要注意的就是编码格式,区要在执行语句前加上这样一句话

<span style="font-family:Microsoft YaHei;font-size:14px;">mysql_query ( 'set names utf8' );</span>
核心代码如下:

<span style="font-family:Microsoft YaHei;font-size:14px;">			$sql = "INSERT INTO `app_bmhjqs`.`db_fml` (`id`, `author`, `icon_url`, `content`, `vote`, `comments`, `up`, `down`) VALUES (NULL, '$z', '$t', '$w', '$d', '$p', '$ds', '$ps');";			// 解决乱码			mysql_query ( 'set names utf8' );			$result = mysql_query ( $sql );</span>

这样一来,获取--->解析--->插入就完成了,效果就是运行一次PHP文件,数据库就添加了糗事百科首页上的糗事!我想可不可以写个定时器,每隔一定时间就运行一次代码,这一点在java我可以实现,在php我不会,毕竟是个没长毛的小鸟!百度吧。。。搜到这样的写法

<span style="font-family:Times New Roman;font-size:14px;">// 定时器// ignore_user_abort (); // run script. in background// set_time_limit ( 0 ); // run script. forever// $interval = 30; // do every 15 minutes..// do {// 	echo date ( 'Y-m-d H:i:s', time () );// 	echo '写入数据库';// 	//getFmlDataToDB ();	// } while ( true );</span>
在文件里加上这样的代码,正好在学校断网前,发布到了SAE上,我没有测试!只能等到第二天来查看结果了!

今天早上,我迫不及待的打开电脑,打开SAE数据库,情况如下:

额滴神!受不鸟了,赶紧把定时器关掉了,写了个按钮触发事件!这样下去,数据库会被挤满的!

好了,PHP爬取糗事百科首页糗事就此完成

如果你感觉这篇Blog对你有所帮助,就点个赞吧!



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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 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.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

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 and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

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.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 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.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)