scrapy框架入门(三)

62 阅读2分钟

今天这篇文章爬取一个简单的网站,通过scrapy框架。

需求分析

目标网站: https://quotes.toscrape.com/
需求: 翻页抓取所有的名人名言,作业,标签
页面分析:
    目标url: https://quotes.toscrape.com/
    请求方式: get
    返回响应内容格式: html -- xpath/bs4
    每一组的内容都是在 div class="quote"
    循环遍历,依次获取每一组的数据
    诗句: 在span标签当中
    作者: small class="author"
    标签内容: 在多个a标签当中

创建scrapy项目

终端运行:

1.创建项目 scrapy startproject get_scrape

2.进入项目中cd get_scrape

3.创建爬虫文件scrapy genspider pac emample.com

代码实现

第一步

将robot协议关掉,因为默认是打开的,但是有这玩意是爬不到数据的,一定要关掉

image.png

第二步

设置请求头 setting里找到

image.png

将ua加进去

image.png

第三步

改域名,因为刚刚写的emample.com是随便写的这里要改掉

image.png

第四步

测试,因为在终端运行很麻烦,所以创建一个文件,用于运行代码

#执行项目文件
from scrapy import cmdline
import os

# 切换到项目根目录
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# 执行爬虫
cmdline.execute(['scrapy', 'crawl', 'pac'])

image.png 然后响应数据就出来了

但是上下还有很多日志文件,如果不想要也很简单,在setting里面加个这个就行了

image.png

第五步

设置爬取字段,在items里

image.png

第六步

数据解析 框架内部已经帮我们集成好了xpath等解析方法,这里不用导包,直接使用即可

import scrapy
#导包,导入储存数据的方法
from get_scrape.items    import GetScrapeItem

class PacSpider(scrapy.Spider):
    name = "pac"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ["https://quotes.toscrape.com/"]

    def parse(self, response):
        # 解析数据
        quotes = response.xpath("//div[@class='quote']")
        for quote in quotes:
           # 实例化对象
            item = GetScrapeItem()
            text = quote.xpath(".//span[@class='text']/text()").get()
            author = quote.xpath(".//small[@class='author']/text()").get()
            tags = quote.xpath(".//div[@class='tags']/a/text()").extract()
            
            item = {
                "text": text,
                "author": author,
                "tags": tags 
            }
            print(item)
            yield item
        

第七步

翻页爬取

if next is not None:
            next = response.urljoin(next)
            print(next)   

            '''- response.follow() :是Scrapy提供的一个便捷方法,用于跟随链接
- callback=self.parse :指定回调函数,表示访问下一页后仍使用当前的parse方法来解析数据'''
            yield response.follow(next, callback=self.parse)

第八步

保存数据 非常简单在start文件里,也就是一开始创建的启动项目文件,改一个东西

#执行项目文件
from scrapy import cmdline
import os

# 切换到项目根目录
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# 执行爬虫
cmdline.execute( "scrapy crawl get_scrape -o scrape.csv".split())

再运行就完工了

image.png

以上面的案例可以看出,scrapy框架还是非常方便的,但是这些功能只是它的冰山一角,具体牛在哪,请看下面的进阶内容。另外,最近学着用了Trae,真的,用了的都说牛逼,大家都去用!!!!这些代码都是用trae写的,功能非常齐全!!!