学习记录:Scrapy爬取斗鱼直播间数据

本文记录了一次使用Python的Scrapy和Selenium爬取斗鱼直播间数据的过程,包括对网站的分析、爬取直播间信息、利用Selenium实现动态翻页以及如何提高爬取速度的改进方法。

前言

学校的实训要求做一个大数据项目,我们的任务是一个斗鱼流量大数据平台。我先爬一下试试。初学Python和scrapy,写的代码有很多问题都没搞定,但是今天解决了一个难题,所以分享一下经历。

对网站的分析

斗鱼的直播间页面
到斗鱼的直播间页面https://www.douyu.com/directory/all,按F12打开开发人员工具,找到我需要的数据,即“在线直播”下面各个直播间的链接、标题、主播名字、热度等。
在这里插入图片描述
网页代码中这些的文字就是我需要的。
在这里插入图片描述
我们需要的内容都在这个li下面,右键它Copy→复制完整的XPath,得到/html/body/section/main/section[2]/div[2]/ul/li[1],接下来就要用到这个。这里去掉最后的[1]得到的/html/body/section/main/section[2]/div[2]/ul/li就是用来查找所有直播间信息框框的XPath

爬取直播间信息

怎么新建项目的就不提了,项目目录如图示:
在这里插入图片描述
setting.py
主要 的设置有下面几项:

ROBOTSTXT_OBEY = False
LOG_LEVEL = 'INFO'
CONCURRENT_REQUESTS = 64
ITEM_PIPELINES = {
   
   
    'douyu.pipelines.DouyuPipeline': 300,
}

斗鱼有反爬虫机制,所以设置不遵守robots.txt;设置log_level不显示DEBUG信息,不然待会运行起来一大堆DEBUG的log;同时处理的数量设置为64;然后开启pipelines.


items.py

import scrapy


class DouyuItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    url = scrapy.Field()
    zone = scrapy.Field()
    user = scrapy.Field()
    hot = scrapy.Field()

我需要的数据是直播间标题、链接、分区、用户名、热度


pipelines.py

import csv


class DouyuPipeline:
    def process_item(self, item, spider):
        with open("doouyu.csv", "a", encoding="utf-8") as fp:
            writer = csv.writer(fp)
            writer.writerow((item['title'], item['url'], item['user'], item['zone'], item['hot']))

输出保存到csv文件


spiders/dy.py

import scrapy
from douyu.items import DouyuItem


class DySpider(scrapy.Spider):
    name = 'dy'
    allowed_domains = ['douyu.com']
    start_urls = ['https://www.douyu.com/directory/all']

    def parse(self, response):
        li_list = response.xpath("/html/body/section/main/section[2]/div[2]/ul/li")

        for li in li_list:
            title = li.xpath("./div/a/div[2]/div[1]/h3/text()").extract_first()
            url = li.xpath("./div/a/@href").extract_first()
            zone = li.xpath("./div/a/div[2]/div[1]/span/text()").extract_first()
            user = li.xpath("./div/a/div[2]/div[2]/h2/div/text()").extract_first()
第1关:Scrapy是一个强大的Python爬虫框架,它能够自动化抓取网页数据并整理成结构化的信息。如果你想将爬取数据存储到MongoDB数据库中,你可以按照以下步骤操作: 1. **安装依赖**: - 安装Scrapy本身:`pip install scrapy` - 安装Scrapy-MongoDB适配器:`pip install scrapy-mongodb` 2. **创建Scrapy项目**: 使用命令行创建一个新的Scrapy项目:`scrapy startproject my_crawler` 3. **配置settings.py**: 在项目的`settings.py`文件中,添加MongoDB的连接设置: ```python MONGO_URI = 'mongodb://localhost:27017/mydatabase' ITEM_PIPELINES = {'my_crawler.pipelines.MongoDBPipeline': 300} ``` 4. **编写管道(Pipeline)**: 创建一个名为`MongoDBPipeline.py`的文件,这是用于处理数据并将其保存到MongoDB的地方。这里你会使用Scrapy的Item Pipeline机制,如示例所示: ```python from pymongo import MongoClient from scrapy.item import Item, Field class MyItem(Item): # 定义你要存储在MongoDB中的字段 class MongoDBPipeline: def __init__(self): self.client = MongoClient(MONGO_URI) self.collection = self.client['mydatabase']['mycollection'] def process_item(self, item, spider): self.collection.insert_one(dict(item)) return item ``` 5. **定义Spider**: 在spiders目录下,创建一个Spider,比如`myspider.py`,并在其中定义下载和解析规则。采集到的数据会自动通过Pipeline传入MongoDB。 6. **运行爬虫**: 最后,在命令行运行你的爬虫:`scrapy crawl myspider` 完成上述步骤后,Scrapy会在每次求成功后将数据存储到指定的MongoDB集合中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值