爬虫——scrapy入门

时间:2022-10-19 04:32:17

scrapy

  • 安装scrapy
pip install scrapy

windows可能安装失败,需要先安装c++库或twisted,pip install twisted

  • 创建项目
scrapy startproject tutorial

该命令将会创建包含下列内容的 tutorial 目录:

tutorial/
scrapy.cfg
tutorial/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
... scrapy.cfg: 项目的配置文件
tutorial/: 该项目的python模块。之后您将在此加入代码。
tutorial/items.py: 项目中的item文件.
tutorial/pipelines.py: 项目中的pipelines文件.
tutorial/settings.py: 项目的设置文件.
tutorial/spiders/: 放置spider代码的目录.
  • 编写第一个爬虫

为了创建一个Spider,您必须继承 scrapy.Spider 类,定义以下三个属性

scrapy genspider dmoz dmoz.com 终端命令可以直接完成这步操作

  • 属性
    • name: 用于区别Spider。 该名字必须是唯一的,您不可以为不同的Spider设定相同的名字
    • start_urls: 包含了Spider在启动时进行爬取的url列表。 因此,第一个被获取到的页面将是其中之一。 后续的URL则从初始的URL获取到的数据中提取
    • parse() 是spider的一个方法。 被调用时,每个初始URL完成下载后生成的
    • Response 对象将会作为唯一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URL的 Request 对象
 import scrapy

 class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
] def parse(self, response):
filename = response.url.split("/")[-2]
with open(filename, 'wb') as f:
f.write(response.body)
  • 爬取
scrapy crawl dmoz

过程:Scrapy为Spider的 start_urls 属性中的每个URL创建了 scrapy.Request 对象,并将 parse 方法作为回调函数(callback)赋值给了Request;Request对象经过调度,执行生成 scrapy.http.Response 对象并送回给spider parse() 方法。


xpath(): 传入xpath表达式,返回该表达式所对应的所有节点的selector list列表 。
css(): 传入CSS表达式,返回该表达式所对应的所有节点的selector list列表.
extract(): 序列化该节点为unicode字符串并返回list。
re(): 根据传入的正则表达式对数据进行提取,返回unicode字符串list列表。
  • scrapy shell
scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/"
  • response
    • response.body:包体
    • response.headers:包头
    • response.xpath():xpath选择器
    • response.css():css选择器
 import scrapy

 class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
] def parse(self, response):
for sel in response.xpath('//ul/li'):
title = sel.xpath('a/text()').extract()
link = sel.xpath('a/@href').extract()
desc = sel.xpath('text()').extract()
print title, link, desc

请使用手机"扫一扫"x