Scrapy 模块
安装
使用 pip 或 在此 下载
- 安装 wheel、lxml、twisted
- 安装 pywin32
- 配置 pywin32 :将
Python安装路径\Lib\site-packages\pywin32_system32
下的两个文件复制到C:\Windows\System32
常用指令
指令 | 功能 |
---|---|
scrapy startproject | 创建爬虫项目 |
scrapy genspider -l | 查看爬虫模板 |
scrapy genspider -t 模板 爬虫文件名 域名 | 创建爬虫 |
scrapy crawl 爬虫文件名 | 运行爬虫 |
scrapy list | 查看有哪些爬虫 |
文件介绍
文件(夹) | 描述 |
---|---|
spiders/ | 存放爬虫 |
items.py | 想要爬取的内容 |
middlewates.py | 中间件 |
pipelines.py | 爬取之后的处理 |
settings.py | 项目设置 |
流程
- 创建爬虫项目
- 编写 items
- 创建爬虫文件
- 编写爬虫文件
- 编写 pipelines
- 配置 settings
例子
# 创建项目
> scrapy startproject ali
# 查看可用模板
> scrapy genspider -l
# 创建爬虫
> scrapy genspider -t basic aliwx aliwx.com.cn
# 查看爬虫
> scrapy list
# 运行
> scrapy crawl aliwx
# items.py
import scrapy
class AliItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
# aliwx.py
import scrapy
from ali.items import AliItem
class AliwxSpider(scrapy.Spider):
name = 'aliwx'
allowed_domains = ['aliwx.com.cn']
start_urls = ['http://www.aliwx.com.cn']
def parse(self, response):
item = AliItem()
item["title"] = response.xpath("//p[@class= 'title']/text()").extract()
yield item
# pipelines.py
from itemadapter import ItemAdapter
class AliPipeline:
def process_item(self, item, spider):
for it in item["title"]:
print("-------")
print(it)
return item
# setting.py
ITEM_PIPELINES = {
'ali.pipelines.AliPipeline': 300,
}
当当爬虫实战
# items.py
import scrapy
class DangdangItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
link = scrapy.Field()
comment = scrapy.Field()
# dang.py
import scrapy
from dangdang.items import DangdangItem
from scrapy.http import Request
class DangSpider(scrapy.Spider):
name = 'dang'
allowed_domains = ['category.dangdang.com']
start_urls = ['http://category.dangdang.com/pg1-cp01.54.02.00.00.00.html']
def parse(self, response):
item = DangdangItem()
item["title"] = response.xpath("//a[@name='itemlist-title']/@title").extract()
item["link"] = response.xpath("//a[@name='itemlist-title']/@href").extract()
item["comment"] = response.xpath("//a[@name='itemlist-title']/@text").extract()
yield item
for i in range(2, 5):
url = "http://category.dangdang.com/pg" + str(i) + "-cp01.54.02.00.00.00.html"
yield Request(url, callback=self.parse)
# pipelines.py
from itemadapter import ItemAdapter
class DangdangPipeline:
def process_item(self, item, spider):
for it in item["title"]:
print(it)
return item
# setting.py
ITEM_PIPELINES = {
'dangdang.pipelines.DangdangPipeline': 300,
}
其他小节笔记
阿里云爬虫项目课程笔记【1】:正则表达式 与 XPath表达式
阿里云爬虫项目课程笔记【2】:Urllib模块 与 糗事百科爬取实战
阿里云爬虫项目课程笔记【3】:腾讯视频评论实战
阿里云爬虫项目课程笔记【4】:Requests 模块 与 云栖社区博文爬虫实战
阿里云爬虫项目课程笔记【6 - 8】:招聘信息、淘宝网商品信息 与 知乎 爬虫实战
阿里云爬虫项目课程笔记【9 & 10】常见的反爬策略与反爬攻克手段、腾讯漫画爬取实战 与 分布式爬虫