抓取网页数据工具(如何编写一个网络爬虫的抓取功能?-八维教育)
优采云 发布时间: 2021-11-06 09:11抓取网页数据工具(如何编写一个网络爬虫的抓取功能?-八维教育)
从各种搜索引擎到日常数据采集,网络爬虫密不可分。爬虫的基本原理很简单。它遍历网络上的网页,抓取感兴趣的数据内容。本篇文章将介绍如何编写一个网络爬虫从头开始抓取数据,然后逐步完善爬虫的爬取功能。
我们使用python 3.x 作为我们的开发语言,只是一点python基础。首先,我们还是从最基本的开始。
工具安装
我们需要安装 python、python requests 和 BeautifulSoup 库。我们使用 Requests 库抓取网页内容,使用 BeautifulSoup 库从网页中提取数据。
-安装python
- 运行 pip 安装请求
- 运行 pip install BeautifulSoup
爬网
完成必要工具的安装后,我们就正式开始编写我们的爬虫了。我们的首要任务是抓取豆瓣上的所有图书信息。举个例子,我们先来看看如何抓取网页的内容。
使用python的requests提供的get()方法,我们可以很方便的获取到指定网页的内容,代码如下:
import requests
if __name__== "__main__":
response = requests.get("https://book.douban.com/subject/26986954/")
content = response.content.decode("utf-8")
print(content)
提取内容
抓取网页内容后,我们要做的就是提取我们想要的内容。在我们的第一个例子中,我们只需要提取书名。首先,我们导入 BeautifulSoup 库。使用BeautifulSoup,我们可以非常简单的提取网页的具体内容。
import requests
from bs4 import BeautifulSoup
if __name__== "__main__":
response = requests.get("https://book.douban.com/subject/26986954/")
content = response.content.decode("utf-8")
#print(content)
soup = BeautifulSoup(content, "html.parser")
# 获取当前页面包含的所有链接
for element in soup.select("a"):
if not element.has_attr("href"):
continue
if not element["href"].startswith("https://"):
continue
print(element["href"])
# 获取更多数据
持续的网络爬行
至此,我们已经能够抓取单个网页的内容,现在让我们看看如何抓取网站的整个内容。我们知道网页是通过超链接相互连接的,我们可以通过链接访问整个网络。所以我们可以从每个页面中提取到其他网页的链接,然后重复抓取新的链接。
import time
import requests
from bs4 import BeautifulSoup
# 保存已经抓取和未抓取的链接
visited_urls = []
unvisited_urls = [ "https://book.douban.com/subject/26986954/" ]
# 从队列中返回一个未抓取的URL
def get_unvisited_url():
while True:
if len(unvisited_urls) == 0:
return None
url = unvisited_urls.pop()
if url in visited_urls:
continue
visited_urls.append(url)
return url
if __name__== "__main__":
while True:
url = get_unvisited_url()
if url == None:
break
print("GET " + url)
response = requests.get(url)
content = response.content.decode("utf-8")
#print(content)
soup = BeautifulSoup(content, "html.parser")
# 获取页面包含的链接,并加入未访问的队列
for element in soup.select("a"):
if not element.has_attr("href"):
continue
if not element["href"].startswith("https://"):
continue
unvisited_urls.append(element["href"])
#print(element["href"])
time.sleep(1)
总结
我们的第一个网络爬虫已经开发完成。它可以抓取豆瓣上的所有书籍,但它也有很多局限性。毕竟,这只是我们的第一个小玩具。在后续的文章中,我们会逐步完善我们爬虫的爬取功能。在后续的文章中,我们会逐步完善我们爬虫的爬取功能。
来源: