吹的这么NB的Python,爬取网页是怎么做到的?

Python

Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的、大型项目的开发。

Python版本差异

Python2的紧箍咒

回望近些年才被 AI 点燃的 Python,其实并非是一门新的语言,它最早于 1989 年底由知名的荷兰计算机程序员 Guido van Rossum 发明,后来作为一门面向对象、直译式计算机程序设计语言于 1991 年面世。其 30 年的发展历程可谓比编程语言界的常青藤 Java 更为久远。

Python分为2.x和3.x版本,而前者在本文编写的前几天就已经嗝屁了,每次使用pip2时都会爆出:

DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won’t be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support

所以这里我们使用Python3。

Python requests库

我们可以使用pip install requests来安装requests库,我们使用:

import requests

来导入requests库,如果在交互式中,我们如果看到没有报错,就证明requests安装完成了。

使用requests中国秦川联盟的主页

我们在脚本中输入:

import requests
requests.get("https://www.qinnational.xyz/")

无反应

然后按F5执行,我们发现程序并没有输出。

这时候,我们加入print输出,将脚本更改为

import requests
print(requests.get("https://www.qinnational.xyz/").content)

爬虫

这时候,我们抓取到了https://www.qinnational.xyz/中国秦川联盟的网页并得到输出:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<!-- Verifications -->
<meta name="baidu-site-verification" content="lw65VVjI6w" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="msvalidate.01" content="2D76DBA9C0B07B52C5A4E01E9C544670" />
<meta name="360-site-verification" content="f2b92e1ed29f39bd884ee129cccee90c" />
<meta name='keywords' content="中国秦川联盟,秦川联盟">
<meta name=description content="中国秦川联盟是一个综合性组织,批准创建了中国晨风社和雨墨局等组织。我们已经和天狼队、米兔联盟、红龙网络安全组织、FREET安全组和萤火虫网安等组织建立合作关系。" >
<link rel="shortcut icon" href="./static/favicon.ico" />
<title>中国秦川联盟</title>
......

这时候我们就成功的模拟了爬虫的工作,虽然各类爬虫譬如百度蜘蛛当然代码更加复杂,基本代码便是如此。

我们必须勤于学习敏于思考,才能把我国建设成富强民主文明和谐美丽的社会主义现代化强国!

原创文章 10 获赞 5 访问量 5021

猜你喜欢

转载自blog.csdn.net/weixin_42660646/article/details/104042766