宝塔山 发表于 2024-8-3 06:26:37

Scrapy 爬取旅游景点相关数据(五)



   本期内容:(1)爬取日本其他城市数据存入数据库(2)爬取景点批评数据
1 爬取其他城市景点数据

只爬取一个城市的数据对于做数据可视化系统大概是不敷的,因为数据样本量少嘛,本期来爬取其他城市的景点数据,前面四期已经打好的精良基础,本期内容非常简单,只需要对项目稍加修改,就可以完成,废话不多说,let’s go。
首先改一下爬虫,把城市作为一个参数,好比如今改为横滨:
start_urls = ['https://place.qyer.com/yokohama/sight/']
city = '横滨'
nation = '日本'
item部分如许写:
item['city'] = self.city
item['nation'] = self.nation
翻页的时候判断下100页以上的不消爬取了,因为这个网站凌驾100页你去点下一页,它也不刷新数据了
            if page_number > 100:
                break
多爬一些数据,后续做旅游分析系统的时候数据多一点系统做出来就好看,我爬取的结果:
https://i-blog.csdnimg.cn/direct/4f69b803cdce4032b593cee875e1c0cc.png
2 爬取批评数据 爬取思绪

之前爬取的数据字段里有个comment_url ,就是为了爬取批评数据作的准备,通过这个字段就可以爬取每个景点的用户批评,例如东京迪士尼景区的用户批评是在这个地址:https://place.qyer.com/poi/V2EJalFnBzRTbQ/review/
通过欣赏器的开发者模式可以大致如何爬取这个页面,其他也类似于景区列表,这个页面也是通过翻页来加载数据的。
下面用一张图来展示爬取流程:
https://i-blog.csdnimg.cn/direct/ea1815bfb99a4aa1b65fa0d1300ecd20.png
首先需要遍历tb_tour表的comment_url字段,循环中去读取每个景点的批评页面, 而爬取批评页面的过程中需要翻页,这内里也涉及一个循环,爬取每页都会去调用一次pipeline进行数据的存储。
这次我们会有两个地方去读取mysql数据库,一个是爬虫,二是管道部分,因此先优化一下数据库的设置,把链接信息写到settings.py里

DB_HOST = 'localhost'
DB_USER = '******'
DB_PASS = '******'
DB_DATABASE = 'scrapy_demo'
DB_CHARSET= 'utf8'
3 编写批评爬虫 初始化部分

首先新建一个爬虫QyCommentSpider ,整个整体的思绪和之前爬取景点的类似,差别之处在于启动的Url需要从数据库里去获取,另外,需要一个专门的管道了处置惩罚数据。先编写部分爬虫
class QyCommentSpider(scrapy.Spider):
    name = 'cmt'
    custom_settings = {
      'ITEM_PIPELINES': {'tutorial2.pipelines.TourCommentPipeline': 300}
    }

    def __init__(self, *args, **kwargs):
      super(QyCommentSpider, self).__init__(*args, **kwargs)
      options = webdriver.ChromeOptions()
      # 这行代码是用于设置 Chrome 浏览器的选项。--headless 参数表示以无头模式(无 GUI 界面)运行 Chrome 浏览器。
      # 无头模式下,浏览器运行在后台,不会显示任何图形界面,从而能够提高爬取效率和性能。这在服务器环境中非常有用,因为服务器通常没有图形界面。
      options.add_argument('--headless')
      LOGGER.setLevel(logging.WARNING)
      # 这行代码是用于指定 ChromeDriver 的路径。ChromeDriver 是 Selenium 用于控制 Chrome 浏览器的驱动程序。
      service = Service('/usr/local/bin/chromedriver')
      self.driver = webdriver.Chrome(options=options, service=service)# 替换为 ChromeDriver 的实际路径

    def start_requests(self):
      # 连接 MySQL 数据库
      db = pymysql.connect(
            host=self.settings.get('DB_HOST'),
            user=self.settings.get('DB_USER'),
            password=self.settings.get('DB_PASS'),
            database=self.settings.get('DB_DATABASE'),
            charset=self.settings.get('DB_CHARSET')
      )

      cursor = db.cursor()
      cursor.execute("SELECT comment_url, id FROM tb_tour")
      start_urls = cursor.fetchall()
      cursor.close()
      db.close()

      for url in start_urls:
            yield scrapy.Request(url=url, callback=self.parse,
                                 meta={'tid': url})
4 编写item 和 管道

class TourCommentItem(scrapy.Item):
    tid = scrapy.Field()
    username = scrapy.Field()
    avatar = scrapy.Field()
    comments = scrapy.Field()
   
# 保存mysql 景点评论
class TourCommentPipeline:

    def process_item(self, item, spider):
      pass
在settings里也增加下新的管道
ITEM_PIPELINES = {
   'tutorial2.pipelines.TourPipeline': 300,
   'tutorial2.pipelines.TourCommentPipeline': 301,
}
5 分析代码 【增补】

做视频的时候发现漏了给出分析的代码了,下面补全


def parse_page(self, page_source, tid):
      response = scrapy.Selector(text=page_source)
      # 生成指纹
      fingerprint = self.get_fingerprint(page_source)
      # 判断指纹是否存在
      if self.fingerprint_exists(fingerprint):
            self.logger.info('指纹已存在,跳过 %s', fingerprint)
            return

      # 保存指纹
      self.save_fingerprint(fingerprint)

      # print(response)
      comments = response.xpath('//ul[@id="commentlist"]/li')
      # print('comments=', comments)
      for comment in comments:
            item = TourCommentItem()
            item['tid'] = tid

            item['username'] = comment.xpath('.//a/span/text()').get().strip()
            item['avatar'] = comment.xpath('.//a/img/@src').get().strip()
            item['comments'] = comment.xpath('.//div[@class="comment clearfix"]/p[@class="content"]').xpath('string(.)').extract()

            print(f"\033}\033[0m")
            print(f"\033}\033[0m")
            # print(f"\033}\033[0m")
            # print(f"\033}\033[0m")

            yield item
6 开启debug

之前我们一直是用命令行来跑scrapy 的,可以在scrapy.cfg同级目录建一个run.py文件
# -*- coding:utf-8 -*-
from scrapy import cmdline
# cmt 对应的是爬虫名
# 在cmd运行 scrapy crawl cmt 同步
cmdline.execute("scrapy crawl cmt".split())
pycharm去执行这个文件,就可以debug运行了。
爬取结果:
https://i-blog.csdnimg.cn/direct/a70ecf7bf00e4638a31d039fe6578529.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Scrapy 爬取旅游景点相关数据(五)