• Python 爬虫—scrapy


    scrapy用于从网站中提取所需数据的开源协作框架。以一种快速、简单但可扩展的方式。

    爬虫框架适合于那种静态页面, js 加载的话,如果你无法模拟它的 API 请求,可能就需要使用 selenium 这种使用无头浏览器的方式来完成你的需求了

    入门

    import scrapy
    
    class BlogSpider(scrapy.Spider):
        name = 'blogspider'
        start_urls = ['https://www.zyte.com/blog/']
    
        def parse(self, response):
            for title in response.css('.oxy-post-title'):
                # 返回对象
                yield {'title': title.css('::text').get()}
    
            for next_page in response.css('a.next'):
                # 返回一个连接,爬虫框架会继续请求这个连接,得到响应后再回调 parse 方法
                yield response.follow(next_page, self.parse)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    运行

    scrapy runspider myspider.py
    
    • 1

    代码中通过 main 方式运行调试

    # _*_ coding: utf-8 _*_
    import os, sys, pprint
    from scrapy.cmdline import execute
    
    
    def build_base_config():
        current_dir_path = os.path.dirname(os.path.abspath(__file__))
        # sys.path.append(current_dir_name)  # 入口文件 与模块查找路径、import 相对路径导入有影响
        print('\n当前路径 PATH:', current_dir_path)
        # pprint.pprint(sys.path)
        filepath, file_name = os.path.split(current_dir_path)
        spiders_name = file_name
        spiders_name = "bestbuy_new_ca"
        return current_dir_path, spiders_name
    
    def run_product_review():
        """
        运行产品评论
        """
        current_dir_path, spiders_name = build_base_config()
        # 结果输出到本地 json 文件
        execute(['scrapy', 'crawl', spiders_name + '-products_review',
                 f'-o{current_dir_path}/temp/product-review.json',
                 '-LDEBUG',
                 f'-apath={current_dir_path}/temp/review-links.json',
                 '-acollect_exist=1'
                 ])
    
    
    if __name__ == '__main__':
        run_product_review()
        pass
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    简单说:使用了 scrapy.cmdline 提供的工具,执行的命令和在命令行中的一致,只是这种方式可以在 idea 工具中进行 debug 调试

    入门和实际开发的不同之处:

    1. 开发上:
      a.入门:例子相对简单,工程结构也不怎么注重
      b.生产:相对复杂,在核心开发上差不多,也是如何去解析 html 结构,工程结构上为了调度和复用,可能会更复杂一点
    2. 调度平台:
      a.有使用一些开源的调度平台,因为是通用
      b.还有的可能会再开源的调度平台上,再包装一层自己的调度平台,仅用来展示(符合产品经理的设计)

    官方对于动态内容的引导

    https://docs.scrapy.org/en/latest/topics/dynamic-content.html

    个人感觉这里提供的知识点还是非常具有参考价值的,简单总结:

    • 使用 scrapy shell 工具定位数据源
    $ scrapy shell "quotes.toscrape.com/scroll"
    (...)
    >>> view(response)
    
    • 1
    • 2
    • 3
    • 使用 scrapy fetch 工具获取响应到文件,这类似与查看网页源代码
    scrapy fetch --nolog https://example.com > response.html
    
    • 1
    • 复制请求:在浏览器中可以将请求复制为 curl 格式,然后可以使用 form_curl() 来使用
    from scrapy import Request
    
    request = Request.from_curl(
        "curl 'https://quotes.toscrape.com/api/quotes?page=1' -H 'User-Agent: Mozil"
        "la/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0' -H 'Acce"
        "pt: */*' -H 'Accept-Language: ca,en-US;q=0.7,en;q=0.3' --compressed -H 'X"
        "-Requested-With: XMLHttpRequest' -H 'Proxy-Authorization: Basic QFRLLTAzM"
        "zEwZTAxLTk5MWUtNDFiNC1iZWRmLTJjNGI4M2ZiNDBmNDpAVEstMDMzMTBlMDEtOTkxZS00MW"
        "I0LWJlZGYtMmM0YjgzZmI0MGY0' -H 'Connection: keep-alive' -H 'Referer: http"
        "://quotes.toscrape.com/scroll' -H 'Cache-Control: max-age=0'")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 解析 JavaScript 代码:html 中有些网站会出现 ,就可以使用
    比如是
    var data = {"field": "value"};
    
    可以使用如下的方式匹配
    pattern = r'\bvar\s+data\s*=\s*(\{.*?\})\s*;\s*\n'
    json_data = response.css('script::text').re_first(pattern)
    json.loads(json_data)
    {'field': 'value'}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    凌恩客户文献|宏基因组binning解析中国浓味白酒窖泥微生物群落MAGs和代谢潜力
    07架构管理之架构评审方法
    ECharts 饼图颜色设置教程 - 4 种方式设置饼图颜色
    Linux
    阿里云 :推出通义大模型编码助手产品【通义灵码】
    SpringBoot中个常见的几个问题
    复习单片机:IIC-EEPROM 实验(内含:1.IIC-EEPROM介绍+2.AT24C02 介绍+3.硬件设计+4.软件设计+5.实验现象)
    社交媒体营销策略——如何病毒式传播:增加受众范围的9个技巧
    我开始使用了Typescript
    uniapp的组件封装与组件间的参数传递
  • 原文地址:https://blog.csdn.net/a1137588003/article/details/132649976