Notebook
  • Study hard and make progress every day
  • Mouka
    • Windows Internal
      • Helper Functions(todo:)
      • Find Kernel Module Address
      • Patch Guard Oops
      • Hook SSDT(Shadow)
      • Restore SSDT(Shadow)
      • Misc
        • Volatile in C
    • AntiCheat
      • Inject Defense
      • Injection Method
    • DriverDevelopment
      • 20180625
      • 20180626-27
    • Python
      • Python Tricks
        • 内置 http 服务器
        • 函数作为变量
        • "is" vs "=="
        • 直接变量值交换
        • 计算代码执行时间
        • 函数参数分解
        • 打印Python字典
        • 命名元组代替class
        • get()方法访问字典
        • 字典排序
        • 一次检查多个标志
        • 合并两个字典
        • re.sub使用替换函数
    • Algorithms
      • Greedy
        • 使括号平衡的最小交换次数
        • 埃及分数
      • DynamicProgramming
        • 0-1 背包问题
      • LeetCode
        • Count Primes
  • Honey
    • Python笔记
      • lxml库
      • os库
      • json文件读写
      • Scrapy
        • Scrapy安装与开始项目
        • Scrapy-Xpath
Powered by GitBook
On this page
  1. Honey
  2. Python笔记
  3. Scrapy

Scrapy安装与开始项目

打开命令行

进入需要创建虚拟环境的所属文件夹

创建虚拟环境:

python -m venv 虚拟环境名称

进入虚拟环境

虚拟环境名\scripts\activate

在虚拟环境中安装包(scrapy)

pip install scrapy

利用包开展项目

scrapy startproject tutorial

备注:scrapy需要c++ 14.0与pywin32(包)

在命令行中运行scrapy的项目,应进入该项目的虚拟环境,再进入第一个toturial(即与idea/venv并行的项目文件)后写scrapy crawl quotes(爬虫的名字),在命令行中选择文件元素使用

scrapy shell 'http://quotes.toscrape.com/page/1'

在css中,使用extract()和exteact_first()方法来得到html文件的元素,或者使用re()方法根据正则表达式提取html文件元素

可以在spriders中写extract等需要的元素,在命令行中执行, 运行爬虫,并存入名为quotes的json文件

scrapy crawl quotes -o quotes.json

找到sprider正在爬的网页使用response.url,在sprider中,url列表名称不能变必须为start_urls

中止正在运行的sprider,ctrl+c,继续该sprider (somespider指sprider名字(PS:此种回复不能续写json)):

scrapy crawl somespider -s JOBDIR=crawls/somespider-1

可续写json的命令,json为原始json名

scrapy crawl answers -s JOBDIR=crawls/answers-1 -o answers.json

爬取的数据写入csv后无法显示中文的问题,可通过导入mongodb数据库再导出解决

可以把网页整个保存成为html文件,方便后期处理:在spider中这样写

def parse(self, response):
    filename = re.sub(r'https://www.pclady.com.cn/wiki/',"",response.url)
    with open(filename, 'wb') as f:
        f.write(response.body)

scrapy的可以将当前url放入spider类的其他方法,其中dont_filter指的可以重复爬取网页。

response.follow(url, callback=self.final_parse,dont_filter=True)
PreviousScrapyNextScrapy-Xpath

Last updated 6 years ago