使用BeautifulSoup和Scrapy框架实现高效的网页爬虫

2023-07-30 框架 爬虫 高效

使用BeautifulSoup实现网页爬虫:

首先需要安装BeautifulSoup模块,可以使用pip install BeautifulSoup4命令进行安装。

下面是一个简单的网页爬虫实例,目的是获取pidancode.com网站的标题和子标题:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "https://pidancode.com"

html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")

title = soup.title
subtitle = soup.h2

print("Website Title:", title.string)
print("Website Subtitle:", subtitle.string)

这段代码的执行结果为:

Website Title: 皮蛋编程 - Python学习与实践
Website Subtitle: 你的Python学习伙伴

使用Scrapy框架实现网页爬虫:

首先需要安装Scrapy框架,可以使用pip install scrapy命令进行安装。

接着,在命令行中输入下面的命令,创建一个Scrapy项目:

scrapy startproject myproject

这会在当前目录下创建一个名为“myproject”的项目文件夹,包含默认的一些文件。

打开“myproject”文件夹,编辑“spiders”文件夹下的“my_spider.py”文件,编写爬虫代码:

import scrapy

class MySpider(scrapy.Spider):
    name = "pidancode"
    start_urls = ["https://pidancode.com/"]

    def parse(self, response):
        title = response.css("title::text").extract_first()
        subtitle = response.css("h2::text").extract_first()

        yield {
            "Website Title": title,
            "Website Subtitle": subtitle,
        }

这段代码使用了Scrapy框架提供的Selector模块,使用CSS选择器提取网页中的数据。

接着,在命令行中输入下面的命令,启动爬虫:

scrapy crawl pidancode -o pidancode.json

这会启动名为“pidancode”的爬虫,将结果输出到名为“pidancode.json”的文件中。执行结果如下所示:

[
    { "Website Title": "皮蛋编程 - Python学习与实践", "Website Subtitle": "你的Python学习伙伴" }
]

这就完成了通过Scrapy框架实现网页爬虫的过程。需要注意的是,Scrapy框架具有更强大的功能,可以实现多线程、代理池等高级功能。

相关文章