基于Python Scrapy的豆瓣Top250电影爬虫程序

Scrapy安装

Python实现一个简单的爬虫程序(爬取图片)_python简单扒图脚本-CSDN博客

创建爬虫项目

创建爬虫项目:

bash 复制代码
scrapy startproject test_spider

创建爬虫程序文件:

bash 复制代码
>cd test_spider\test_spider\spiders
>scrapy genspider doubanSpider movie.douban.com

编写爬虫程序

分析网址:

bash 复制代码
https://movie.douban.com/top250?start=25&filter=

其中,start=25是分页信息,一共有10页,每页25个电影记录,start数值为0、25、50......225。

python 复制代码
for i in range(0,24,25):
            req = "https://movie.douban.com/top250?start={}&filter=".format(i)
            yield scrapy.Request(url=req, meta={'url': req}, headers=self.headers,callback=self.parse)
            time.sleep(2) 

提取电影网址、中文名、外文名:

python 复制代码
html_data = response.body
sp = BeautifulSoup(html_data, 'html.parser')
list = sp.find(class_='grid_view').find_all('li')
for one in list:
    link = one.find(class_='info').find(class_='hd').find('a')['href']
    print(link)
            
    titles =  one.find_all(class_='title')
    title_zh =titles[0].text.strip().replace(',',' ')
    title_en = ''
    if len(titles)>1:
         title_en = titles[1].text.strip().replace(',',' ').lstrip('/')
    print(title_zh,title_en)

提取导演、演员信息:

python 复制代码
bd = one.find(class_='info').find(class_='bd')
p1 = bd.find_all('p')[0].text.strip().replace('\n','').replace('\r','').replace(',',' ')
print(p1)

提取评分信息:

python 复制代码
spans = bd.find(class_='star').find_all('span')
score = spans[1].text
num = spans[3].text.replace('人评价','')
print(score,num)

写入csv文件:

python 复制代码
with open('movies.csv','a+',encoding='utf-8') as f:
      f.write('网址,中文名,外文名,导演,评分,评价人数\n')

with open('movies.csv','a+',encoding='utf-8') as f:
      f.write('{},{},{},{},{},{}\n'.format(link,title_zh,title_en,p1,score,num))

完整代码:

python 复制代码
import scrapy
from bs4 import BeautifulSoup
import time


class DoubanspiderSpider(scrapy.Spider):
    name = "doubanSpider"
    allowed_domains = ["movie.douban.com"]
    start_urls = ["https://movie.douban.com"]
    
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36','Cookie': ''}

    def start_requests(self):   
        with open('movies.csv','a+',encoding='utf-8') as f:
                f.write('网址,中文名,外文名,导演,评分,评价人数\n')
                
        for i in range(0,24,25):
            req = "https://movie.douban.com/top250?start={}&filter=".format(i)
            yield scrapy.Request(url=req, meta={'url': req}, headers=self.headers,callback=self.parse)
            time.sleep(2) 
        
    def parse(self, response):
        print("========= parse ==============")
        html_data = response.body
        sp = BeautifulSoup(html_data, 'html.parser')
        list = sp.find(class_='grid_view').find_all('li')
        for one in list:
            link = one.find(class_='info').find(class_='hd').find('a')['href']
            print(link)
            
            titles =  one.find_all(class_='title')
            title_zh =titles[0].text.strip().replace(',',' ')
            title_en = ''
            if len(titles)>1:
                title_en = titles[1].text.strip().replace(',',' ').lstrip('/')
            print(title_zh,title_en)
            
            bd = one.find(class_='info').find(class_='bd')
            p1 = bd.find_all('p')[0].text.strip().replace('\n','').replace('\r','').replace(',',' ')
            print(p1)
            
            spans = bd.find(class_='star').find_all('span')
            score = spans[1].text
            num = spans[3].text.replace('人评价','')
            print(score,num)
            
            with open('movies.csv','a+',encoding='utf-8') as f:
                f.write('{},{},{},{},{},{}\n'.format(link,title_zh,title_en,p1,score,num))
            
  
  

运行爬虫程序:

scrapy crawl doubanSpider

生成的csv文件如下:

相关推荐
程序员阿超的博客2 分钟前
Python 数据分析与机器学习入门 (五):Matplotlib 数据可视化基础
python·信息可视化·数据分析·matplotlib·数据可视化·python教程·pyplot
站大爷IP18 分钟前
Python 办公实战:用 python-docx 自动生成 Word 文档
python
MO2T43 分钟前
使用 Flask 构建基于 Dify 的企业资金投向与客户分类评估系统
后端·python·语言模型·flask
慢热型网友.1 小时前
用 Docker 构建你的第一个 Python Flask 程序
python·docker·flask
Naiva1 小时前
【小技巧】Python + PyCharm 小智AI配置MCP接入点使用说明(内测)( PyInstaller打包成 .exe 可执行文件)
开发语言·python·pycharm
云动雨颤1 小时前
Python 自动化办公神器|一键转换所有文档为 PDF
运维·python
梅孔立1 小时前
yum update 报错 Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64 等解决办法
linux·python·centos
前端付豪1 小时前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤1 小时前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
源码站~2 小时前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐