scrapy框架爬取豆瓣top250电影排行榜(下)

(3)在 pipeline.py 文件中对数据进行存储,此程序先写 入 txt 文件中,是为了判断该程序是否能正确爬取出数据。 此处使用了 json 库,使用 ensure_ascii = False,能够确 保非 ASCII 字符(如中文)的数据写入 txt 文件中。

python 复制代码
import json
class DoubanPipeline:
    def open_spider(self,spider):
        self.f = open('maoer1.json','w',encoding='utf-8')
    def process_item(self, item, spider):
        json_str = json.dumps(dict(item),ensure_ascii=False) + '\n'
        self.f.write(json_str)
        return item
    def close_spider(self,spider):
        self.f.close()

(4)在 setting.py 文件中设置优先级。

此外,在我调试的过程中,我发现得做反爬措施。

(5)在此项目下创建一个 main.py 文件,用于调试。

python 复制代码
import os.path
import sys
from scrapy.cmdline import execute
currentFile = os.path.abspath(__file__)
currentPath = os.path.dirname(currentFile)
# print(currentPath)
sys.path.append(currentPath)
execute(["scrapy","crawl","db"])

(6)最终得到的数据如下(json 文件中):

(7)将数据转存至 mysql 中,使用 pymysql 成功连接数据 库后,通过 sql 语句 insert into 表名 values(值)将数 据进行保存。

python 复制代码
import mysql.connector
import json

conn = mysql.connector.connect(
    host="127.0.0.1",
    user="root",
    password="010208",
    database="spider",
    port = 3306,
    charset = "utf8"
)

cursor = conn.cursor()

with open('maoer1.json', 'r') as file:
    data = json.load(file)
    for entry in data:
        description = entry.get('description', '')  # 确保title字段存在
        movie_name = entry.get('movie_name', '')
        director = entry.get('director', '')
        score = entry.get('score', '')

        sql = "INSERT INTO spider10 (description,movie_name,director,score) VALUES (%s,%s,%s,%s)"
        cursor.execute(sql, (description,movie_name,director,score))
conn.commit()

cursor.close()
conn.close()

(8)结果展示

三.数据可视化

本题根据现有数据,做了柱状图和词云图。(好像不是很好看)

四.应用场景

通过对豆瓣网站进行数据爬取并进行可视化分析,我们可以看到,当代社会中人们喜欢的影视作品种类多样,评分较高,质量较高。希望该网站进行推出优秀作品,丰富人们的闲暇生活。


ok,这就是完整的程序说明,重点,我自己写的!

相关推荐
B站_计算机毕业设计之家6 天前
python舆情分析可视化系统 情感分析 微博 爬虫 scrapy爬虫技术 朴素贝叶斯分类算法大数据 计算机✅
大数据·爬虫·python·scrapy·数据分析·1024程序员节·舆情分析
深兰科技7 天前
深兰科技法务大模型亮相,推动律所文书处理智能化
人工智能·scrapy·beautifulsoup·scikit-learn·pyqt·fastapi·深兰科技
龙腾AI白云9 天前
大模型-7种大模型微调方法 上
scrapy·scikit-learn·pyqt
万粉变现经纪人11 天前
如何解决 pip install -r requirements.txt 子目录可编辑安装缺少 pyproject.toml 问题
开发语言·python·scrapy·beautifulsoup·scikit-learn·matplotlib·pip
万粉变现经纪人11 天前
如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
万粉变现经纪人12 天前
如何解决 pip install -r requirements.txt 私有仓库认证失败 401 Unauthorized 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
深蓝电商API13 天前
快速上手 Scrapy:5 分钟创建一个可扩展的爬虫项目
爬虫·python·scrapy
深蓝电商API22 天前
将爬虫部署到服务器:Scrapy+Scrapyd 实现定时任务与监控
服务器·爬虫·scrapy
数据牧羊人的成长笔记22 天前
python爬虫scrapy框架使用
爬虫·python·scrapy
MongoVIP24 天前
Scrapy爬虫实战:正则高效解析豆瓣电影
python·scrapy