Python爬虫入门,快速抓取大规模数据

大到各类搜索引擎,小到日常数据采集,都离不开网络爬虫。爬虫的基本原理很简单,遍历网络中网页,抓取感兴趣的数据内容。这篇文章会从零开始介绍如何编写一个网络爬虫抓取数据,然后会一步步逐渐完善爬虫的抓取功能。

我们使用python 3.x作为我们的开发语言,有一点python的基础就可以了。 首先我们还是从最基本的开始。

工具安装

我们需要安装python,python的requests和BeautifulSoup库。我们用Requests库用抓取网页的内容,使用BeautifulSoup库来从网页中提取数据。
- 安装python
- 运行pip install requests
- 运行pip install BeautifulSoup

抓取网页

完成必要工具安装后,我们正式开始编写我们的爬虫。我们的第一个任务是要抓取所有豆瓣上的图书信息。我们以https://book.douban.com/subject/26986954/为例,首先看看开如何抓取网页的内容。

使用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)

总结

我们的第一个网络爬虫就已经开发完成了。它可以抓取豆瓣上的所有图书,但也有很多局限性,毕竟它只是我们的第一个小玩具。在后续的文章中我们会逐步完善我们的爬虫的抓取功能。在后续的文章中我们会逐步完善我们的爬虫的抓取功能。

Source: https://www.toutiao.com/i6550549917197140493/

猜你喜欢

转载自blog.csdn.net/nj_kevin_peng/article/details/80216290