Python爬虫爬取豆瓣电影短评(爬虫入门,Scrapy框架,Xpath解析网站,jieba分词)

声明:以下内容仅供学习参考,禁止用于任何商业用途

很久之前就想学爬虫了,但是一直没机会,这次终于有机会了

主要参考了《疯狂python讲义》的最后一章

首先安装Scrapy:

pip install scrapy

然后创建爬虫项目:

scrapy startproject 项目名

然后项目里面大概是长这样的:

__pycache__是python缓存,可以不管

scrapy.cfg是scrapy框架自带的配置文件,这个项目里面可以不用改

settings.py里面是爬虫的设置,可以在里面设置爬虫模仿的浏览器型号,以及访问一个页面的延迟(防止被反爬虫),以及是否遵循爬虫规则、是否使用cookies等等:

# Scrapy settings for exp1 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = "exp1"

SPIDER_MODULES = ["exp1.spiders"]
NEWSPIDER_MODULE = "exp1.spiders"


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "exp1 (+http://www.yourdomain.com)"

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 2
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
   'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win 64; x64; rv:61.0) Gecko/20100101Firefox/61.0',
   'Accept' : 'text/htmp,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "exp1.middlewares.Exp1SpiderMiddleware": 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "exp1.middlewares.Exp1DownloaderMiddleware": 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    "scrapy.extensions.telnet.TelnetConsole": None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   "exp1.pipelines.Exp1Pipeline": 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
AUTOTHROTTLE_ENABLED = True
# The initial download delay
AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = "httpcache"
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"

# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

爬虫需要爬取的内容定义在items.py里面:

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class Exp1Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # 电影名
    film_name = scrapy.Field()
    # 评论用户名
    user_name = scrapy.Field()
    # 评论时间
    comment_time =scrapy.Field()
    # 评论内容
    comment = scrapy.Field()
    

middlewares.py应该是中间件的定义,不是很明白它的工作原理,应该也不用改

pipelines.py是将爬取到的内容进行输出保存等处理的管道,也负责一些预处理和后处理的任务,例如把文件保存为json格式:

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class Exp1Pipeline(object):
    def __init__(self):
        self.json_file = open("data6.json","wb+")
        self.json_file.write('[\n'.encode("utf-8"))
    def close_spider(self, spider):
        print('--------关闭文件--------')
        self.json_file.seek(-2,1)
        self.json_file.write('\n]'.encode("utf-8"))
        self.json_file.close()
    def process_item(self, item, spider):
        print("电影名: ",item['film_name'])
        print("评论用户: ",item['user_name'])
        print("评论时间: ",item['comment_time'])
        print("评论内容: ",item['comment'])
        text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
        self.json_file.write(text.encode("utf-8"))

spiders文件夹里面主要用来存储爬虫的主体

爬虫中的访问网页可以直接用scrapy.Request(网址,回调函数名,传参内容(可选))接口进行访问下一个网页。

接下来就是愉快的解析网站时间

由于本人刚入门爬虫技术有限,但是又时间紧迫,所以就只爬了豆瓣top250的电影的短评

首先进入top250的界面按F12查看源码

我们在榜单需要爬取的只有当前页的所有电影链接和下页的链接

我们可以使用scrapy shell协助我们解析网站

首先在终端输入:

scrapy shell -s USER_AGENT='Mozilla/5.0' 网址

接下来就会出现一个很酷的scrapy终端:

接下来我们先学习一下Xpath的用法

在F12打开的右半边窗口中,点击选择按钮

选择一个幸运的网页对象,点击一下

可以发现右侧窗口自动定位到了网页对应的源码

我们只需要从上到下找这些朝下的小三角形,就知道我们选择的内容具体位于哪一层

最终发现是位于:(电影网址)

body->div(id="wrapper")->div(id="content")->div->div(class="article")->ol

->li->div->div(class="info")->div(class="hd")->a节点的href属性

然后把上面这段话转换为Xpath的表达方式就是:

response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/ol/li/div/div[@class="info"]/div[@class="hd"]/a/@href')

具体解释一下:

// 表示匹配任意位置的节点

/ 表示匹配根节点

. 表示匹配当前位置的节点

.. 表示匹配父节点

@ 表示匹配属性

[] 里面表示对当前节点属性的限制(需要加限制的节点一般都是同层级下有相同节点名的节点)

然后把这段话输入进scrapy shell

发现它查出来了一大堆奇奇怪怪的东西:

这其实只是我们没有对内容进行解包,对Xpath的结果调用一下.extract()函数就行了

然后就会发现它的内容是一个列表:

接下来我们只需要依葫芦画瓢就行,把剩下的网站内容依次解析即可

至于为什么没有爬长评,是因为不会处理javascript的网站,但是短评就可以直接解析获取

不过selenium是可以做到的,具体怎么做还需要进一步的学习(挖坑)

但是selenium速度似乎好像会慢一些?

最后就是一些写爬虫的SB错误

之前不太理解yield的机制,搞了半天,发现爬虫爬取的顺序还是有很大问题,结果是用了全局变量导致它发生数据读写冲突了然后就寄了,最后通过Request传参,再用dict保存每个回调函数中获取的下一页位置,这才把问题解决了。另外那个cnt是因为豆瓣似乎限制了短评查看只能查看前10页,后面会无权访问?反正加一下也不是什么大事,但是也要注意不要使用全局变量。

温馨提示:这个代码爬两万条左右短评就会被封号(为了完成5w条的作业要求,被迫封了两个ip)(反反爬虫技术还是太菜了)似乎豆瓣并不是通过ip访问频率来判断爬虫的,而是用ip访问总次数来判断的???

dbspd.py:

import scrapy
from exp1.items import Exp1Item

class DoubanSpider(scrapy.Spider):
    name = 'douban'
    allowed_domain = ['movie.douban.com']
    start_urls = ['https://movie.douban.com/top250?start=0&filter=']
    comment_page_sub = '/comments?sort=time&status=P'
    cnt = {}
    film_pre = {}
    def parse_film(self, response):
        film_name = (response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/h1/text()').extract())[0].split(" ")[0]
        self.film_pre[film_name] = response.meta['fp']
        user_name_list = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/div[@id="comments"]/div/div[@class="comment"]/h3/span[@class="comment-info"]/a/text()').extract()
        comment_time_list = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/div[@id="comments"]/div/div[@class="comment"]/h3/span[@class="comment-info"]/span[@class="comment-time "]/text()').extract()
        comment_list = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/div[@id="comments"]/div/div[@class="comment"]/p/span/text()').extract()
        for (user_name,comment_time,comment) in zip(user_name_list,comment_time_list,comment_list):
            item = Exp1Item()
            item['film_name'] = film_name
            item['user_name'] = user_name
            item['comment_time'] = comment_time.split(" ")[20] + " " + comment_time.split(" ")[21][0:8]
            item['comment'] = comment
            yield item
        new_links_sub = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/div[@id="comments"]/div[@id="paginator"]/a[@class="next"]/@href').extract()
        this_film_pre = self.film_pre.get(film_name, self.film_pre)
        this_film_cnt = self.cnt.get(film_name, 0)
        if(this_film_cnt < 8):
            print("next_page url:",this_film_pre + "comments" + new_links_sub[0])
            self.cnt[film_name] = this_film_cnt + 1
            yield scrapy.Request(this_film_pre + "comments" + new_links_sub[0], callback=self.parse_film, meta={'fp':self.film_pre[film_name]})
    def parse(self, response):
        film_list = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/ol/li/div/div[@class="info"]/div[@class="hd"]/a/@href').extract()
        for film_pre in film_list:
            yield scrapy.Request(film_pre + self.comment_page_sub , callback=self.parse_film, meta={'fp':film_pre})
        new_links_sub = response.xpath('//body/div[@id="wrapper"]/div[@id="content"]/div/div[@class="article"]/div[@class="paginator"]/span[@class="next"]/a/@href').extract()
        print("next_rank_page url:","https://movie.douban.com/top250" + new_links_sub[0])
        yield scrapy.Request("https://movie.douban.com/top250" + new_links_sub[0], callback=self.parse)

最后用命令

scrapy crawl douban

就可以运行我们的爬虫啦!!

最后的最后,再提一嘴分词

先装一个jieba库

pip install jieba

然后直接开用lcut()函数就行了,禁用词列表在stop.txt中,一行一个

另外不知道为什么换行等一些空字符也会出现在分词结果中,所以还得单独处理一下。

import jieba
import json
stop = open("stop.txt", "r", encoding='utf-8').read()
stop = stop.splitlines()
# print(stop)

txt = open("film_comment_data.txt", "r", encoding='utf-8').read()
d = json.loads(txt)
cnt = 0
word_file = open("word.txt","wb+")
for item in d:
    words = jieba.lcut(item['comment'])
    print(cnt)
    cnt+=1
    for word in words:
        if word in stop:
            pass
        else:
            if word != "\n":
                word = word + "\n"
                word_file.write(word.encode("utf-8"))
word_file.close()

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python编写爬虫程序,通过豆瓣电影网站结构和API接口,获取电影相关信息,包括电影名称、导演、演员、评分、评论等。可以使用Python的第三方库,如requests、BeautifulSoup、Scrapy等,来实现爬取解析的功能。同时,需要注意遵守网站爬虫规则和法律法规,避免对网站造成不必要的影响和风险。 ### 回答2: 豆瓣电影是一个非常受欢迎的电影社区,积累了大量用户贡献的电影数据,而top250更是公认的经典代表。使用爬虫技术,我们可以轻松地获取这些珍贵的数据并进行分析。 Python作为一种简单易用的编程语言,非常适合用于爬虫开发。我们可以借助Python的一些爬虫库来进行电影数据的爬取。下面,我将结合具体的代码段来介绍如何使用Python爬虫获取豆瓣电影top250的数据。 首先,你需要安装Python,并下载一些常用的爬虫库,如requests、beautifulsoup等。更进一步地,你可以通过使用Scrapy框架来进行更加高效的开发。 在开始具体编写代码前,我们需要先确定爬取的目标和需求。豆瓣电影top250的面由25个面构成,每个面都展示了10电影信息。因此,我们需要先定义一个爬取面的函数: ```python def getPages(start, num): url = 'https://movie.douban.com/top250?start=' + str(start) + '&filter=' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') items = soup.select('.item') movies = [] for item in items: movie = [] movie.append(item.select('.title')[0].text.replace(' ', '').replace('\n', '')) movie.append(item.select('.rating_num')[0].text) movie.append(item.select('.quote')[0].text.replace('。', '')) movies.append(movie) return movies ``` 这个函数使用了requests和beautifulsoup库,在请求之后对面进行解析,最终将所需的电影信息打包成一个嵌套列表返回。getPages()函数需要传入两个参数,分别对应每个面的起始位置和需要获取多少个电影信息。 接下来,我们可以通过这个函数来获取所有的电影信息了。我们可以定义一个爬取全部数据的函数: ```python def getAllMovies(num): movies = [] for start in range(0, num + 1, 25): pages = getPages(start, 25) movies.extend(pages) return movies ``` 这个函数在循环调用了上述的getPages()函数,并将返回值拼接到一个列表。直到爬取到指定数量的电影信息。 以上就是一个简单的Python爬虫脚本了,你只需要运行这个脚本,并指定需要爬取电影数量,就可以获取到豆瓣电影top250的全部数据了。不仅如此,你还可以将数据进行存储和处理,从而实现更多有趣的功能。 ### 回答3: Python爬虫是一种自动化程序,可用于在网站上进行数据抓取。豆瓣电影是一个非常流行的在线社区,提供了各种电影信息,包括电影评价和用户评价。本文将介绍如何使用Python爬虫程序,从豆瓣电影网站上抓取Top250电影信息。 1.准备工作 在编写Python爬虫之前,我们需要下载并安装Python运行环境,以及必要的第三方库(如Requests和BeautifulSoup)。 2.了解目标网站 在开始编写爬虫之前,我们需要了解目标网站的网结构和数据存储方式。在该网站上,每个电影都有自己的面。每个面都包含了电影的一些基本信息,如电影名称、导演、演员、评分等。 3.识别目标 如果要爬取Top250电影信息,我们需要找到豆瓣电影Top250面的URL,通过浏览该面的HTML源代码,识别我们需要抓取的信息在哪里。可以使用浏览器开发者工具(例如Chrome浏览器的开发者工具)来帮助识别。 4.编写爬虫程序 使用Python编写爬虫程序,我们需要首先发送一个HTTP请求到目标URL,并获取该URL的HTML源代码。可以使用Requests库来发送HTTP请求。然后,我们使用BeautifulSoup库解析HTML源代码,并提取我们需要的内容。最后,我们将提取的数据存储到文件,或将其添加到数据库。 5.处理错误和异常 在爬取过程,可能会遇到各种问题和错误。比如,目标网站可能会将我们的请求拒绝,或者是HTML源代码不兼容我们的解析程序。我们需要适当地处理这些错误并调整我们的程序。 6.总结 Python爬虫是一种非常有用的工具,可以向我们提供大量的数据资源。在编写爬虫程序时,我们需要注意一些法律和道德问题,如尊重目标网站的服务条款,避免使用爬虫程序造成危害等。另外,我们需要维护好我们的程序,确保其在长期运行保持稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值