首页 技术 正文
技术 2022年11月10日
0 收藏 806 点赞 2,435 浏览 5081 个字

scrapy是用python写的一个库,使用它可以方便的抓取网页。

主页地址http://scrapy.org/

文档 http://doc.scrapy.org/en/latest/index.html

安装 sudo pip install scrapy

一个简单的教程 http://doc.scrapy.org/en/latest/intro/tutorial.html

如果你对这些概念有了解,使用上面的教程会比较容易. 它们是json, xpath, 正则表达式,

生成项目

scrapy提供一个工具来生成项目,生成的项目中预置了一些文件,用户需要在这些文件中添加自己的代码。

打开命令行,执行:scrapy startproject tutorial,生成的项目类似下面的结构

python scrapy 基础

tutorial/
scrapy.cfg
tutorial/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
...

python scrapy 基础

scrapy.cfg是项目的配置文件

用户自己写的spider要放在spiders目录下面,一个spider类似

python scrapy 基础

from scrapy.spider import BaseSpiderclass DmozSpider(BaseSpider):
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]
open(filename, 'wb').write(response.body)

python scrapy 基础

name属性很重要,不同spider不能使用相同的name

start_urls是spider抓取网页的起始点,可以包括多个url

parse方法是spider抓到一个网页以后默认调用的callback,避免使用这个名字来定义自己的方法。

当spider拿到url的内容以后,会调用parse方法,并且传递一个response参数给它,response包含了抓到的网页的内容,在parse方法里,你可以从抓到的网页里面解析数据。上面的代码只是简单地把网页内容保存到文件。

开始抓取

你可以打开命令行,进入生成的项目根目录tutorial/,执行 scrapy crawl dmoz, dmoz是spider的name。

解析网页内容

scrapy提供了方便的办法从网页中解析数据,这需要使用到HtmlXPathSelector

python scrapy 基础

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelectorclass DmozSpider(BaseSpider):
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):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//ul/li')
for site in sites:
title = site.select('a/text()').extract()
link = site.select('a/@href').extract()
desc = site.select('text()').extract()
print title, link, desc

python scrapy 基础

HtmlXPathSelector使用了Xpath来解析数据

//ul/li表示选择所有的ul标签下的li标签

a/@href表示选择所有a标签的href属性

a/text()表示选择a标签文本

a[@href=”abc”]表示选择所有href属性是abc的a标签

我们可以把解析出来的数据保存在一个scrapy可以使用的对象中,然后scrapy可以帮助我们把这些对象保存起来,而不用我们自己把这些数据存到文件中。我们需要在items.py中添加一些类,这些类用来描述我们要保存的数据

from scrapy.item import Item, Fieldclass DmozItem(Item):
title = Field()
link = Field()
desc = Field()

然后在spider的parse方法中,我们把解析出来的数据保存在DomzItem对象中。

python scrapy 基础

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelectorfrom tutorial.items import DmozItemclass DmozSpider(BaseSpider):
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):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//ul/li')
items = []
for site in sites:
item = DmozItem()
item['title'] = site.select('a/text()').extract()
item['link'] = site.select('a/@href').extract()
item['desc'] = site.select('text()').extract()
items.append(item)
return items

python scrapy 基础

在命令行执行scrapy的时候,我们可以加两个参数,让scrapy把parse方法返回的items输出到json文件中

scrapy crawl dmoz -o items.json -t json

items.json会被放在项目的根目录

让scrapy自动抓取网页上的所有链接

上面的示例中scrapy只抓取了start_urls里面的两个url的内容,但是通常我们想实现的是scrapy自动发现一个网页上的所有链接,然后再去抓取这些链接的内容。为了实现这一点我们可以在parse方法里面提取我们需要的链接,然后构造一些Request对象,并且把他们返回,scrapy会自动的去抓取这些链接。代码类似:

python scrapy 基础

class MySpider(BaseSpider):
name = 'myspider'
start_urls = (
'http://example.com/page1',
'http://example.com/page2',
) def parse(self, response):
# collect `item_urls`
for item_url in item_urls:
yield Request(url=item_url, callback=self.parse_item) def parse_item(self, response):
item = MyItem()
# populate `item` fields
yield Request(url=item_details_url, meta={'item': item},
callback=self.parse_details) def parse_details(self, response):
item = response.meta['item']
# populate more `item` fields
return item

python scrapy 基础

parse是默认的callback, 它返回了一个Request列表,scrapy自动的根据这个列表抓取网页,每当抓到一个网页,就会调用parse_item,parse_item也会返回一个列表,scrapy又会根据这个列表去抓网页,并且抓到后调用parse_details

为了让这样的工作更容易,scrapy提供了另一个spider基类,利用它我们可以方便的实现自动抓取链接. 我们要用到CrawlSpider

python scrapy 基础

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractorclass MininovaSpider(CrawlSpider):    name = 'mininova.org'
allowed_domains = ['mininova.org']
start_urls = ['http://www.mininova.org/today']
rules = [Rule(SgmlLinkExtractor(allow=['/tor/\d+'])),
Rule(SgmlLinkExtractor(allow=['/abc/\d+']), 'parse_torrent')] def parse_torrent(self, response):
x = HtmlXPathSelector(response) torrent = TorrentItem()
torrent['url'] = response.url
torrent['name'] = x.select("//h1/text()").extract()
torrent['description'] = x.select("//div[@id='description']").extract()
torrent['size'] = x.select("//div[@id='info-left']/p[2]/text()[2]").extract()
return torrent

python scrapy 基础

相比BaseSpider,新的类多了一个rules属性,这个属性是一个列表,它可以包含多个Rule,每个Rule描述了哪些链接需要抓取,哪些不需要。这是Rule类的文档http://doc.scrapy.org/en/latest/topics/spiders.html

这些rule可以有callback,也可以没有,当没有callback的时候,scrapy简单的follow所有这些链接.

pipelines.py的使用

在pipelines.py中我们可以添加一些类来过滤掉我们不想要的item,把item保存到数据库。

python scrapy 基础

from scrapy.exceptions import DropItemclass FilterWordsPipeline(object):
"""A pipeline for filtering out items which contain certain words in their
description""" # put all words in lowercase
words_to_filter = ['politics', 'religion'] def process_item(self, item, spider):
for word in self.words_to_filter:
if word in unicode(item['description']).lower():
raise DropItem("Contains forbidden word: %s" % word)
else:
return item

python scrapy 基础

如果item不符合要求,那么就抛一个异常,这个item不会被输出到json文件中。

要使用pipelines,我们还需要修改settings.py

添加一行

ITEM_PIPELINES = ['dirbot.pipelines.FilterWordsPipeline']

现在执行scrapy crawl dmoz -o items.json -t json,不符合要求的item就被过滤掉了

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,997
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,356
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,139
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848