Python最广泛的应用场景之一便是爬虫。爬虫可将网页内容批量处理。今天,我们就写一个爬取网站源码的项目练练手。
一、工具
本次爬取使用PythonCompiler中文版,其他版本的Python也可以使用。
二、安装第三方库
本次开发需 requests库
安装命令(Windows):python -m pip install requests
三、开发过程
首先我们可以使用requests库进行代码爬取,以Python官网为例:
source = requests.get("http://www.python.org/).content.decode()
当然,一次只能获取一个网站的源码,功能十分有限。所以,我们可以使用while循环进行多次处理:
while True:
a=input("输入你的网址:")
source = requests.get(a).content.decode()
print("The source:", source)
这样,我们便生成了一个可以多次利用的网站源码爬取神器。
代码如下:
import requests
while True:
a=input("输入你的网址:")
source = requests.get(a).content.decode()
print("The source:", source)
运行结果:
然后输入网址(以http或https开头)即可。
以上就是一个简单的爬虫项目,可以爬取网站的源码,希望大家慎用。