Scrapy框架--第二个爬虫项目

目的

http://books.toscrape.com/爬取书本的信息:

  • 书名
  • 价格
  • 评价等级
  • 产品编码
  • 库存量
  • 评价数量

    页面分析

    除了通常使用的chrome开发者工具,我们还使用scrapy自带的shell命令,来测试 XPath 或 CSS 表达式

注意1:chrome分析中会出现copyxpath抓取出错的问题,去掉xpath中的tbody即可

注意2:chrome copy定位到具体的那个点,如果要爬取全部的信息请注意元素后面[]中的内容

例如:

1
2
3
4
# 该xpath只能爬取第一个li元素下的article元素(chrome xpathcopy)
le = LinkExtractor(restrict_xpaths='//*[@id="default"]/div/div/div/div/section/div[2]/ol/li[1]/article')
# 将li[]中的内容删去,则为爬取全部li元素下的article元素(经过修改)
le = LinkExtractor(restrict_xpaths='//*[@id="default"]/div/div/div/div/section/div[2]/ol/li/article')

scrapy shell <url> --nolog,例如在我们的例子中:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
MacBook-Pro:pachong mac$ scrapy shell http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html --nolog
2018-05-24 10:06:33 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: pachong)
2018-05-24 10:06:33 [scrapy.utils.log] INFO: Versions: lxml 4.1.1.0, libxml2 2.9.7, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.5.0, Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33) - [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)], pyOpenSSL 17.5.0 (OpenSSL 1.0.2o 27 Mar 2018), cryptography 2.1.4, Platform Darwin-17.5.0-x86_64-i386-64bit
2018-05-24 10:06:33 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'pachong', 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter', 'LOGSTATS_INTERVAL': 0, 'NEWSPIDER_MODULE': 'pachong.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['pachong.spiders']}
2018-05-24 10:06:33 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.memusage.MemoryUsage']
2018-05-24 10:06:33 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-05-24 10:06:33 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-05-24 10:06:33 [scrapy.middleware] INFO: Enabled item pipelines:
['pachong.pipelines.PachongPipeline', 'pachong.pipelines.DuplicatesPipeline']
2018-05-24 10:06:33 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-05-24 10:06:33 [scrapy.core.engine] INFO: Spider opened
2018-05-24 10:06:35 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://books.toscrape.com/robots.txt> (referer: None)
2018-05-24 10:06:36 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html> (referer: None)
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x1071174a8>
[s] item {}
[s] request <GET http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html>
[s] response <200 http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html>
[s] settings <scrapy.settings.Settings object at 0x107d167b8>
[s] spider <DefaultSpider 'default' at 0x107fd6710>
[s] Useful shortcuts:
[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
[s] view(response) View response in a browser
In [1]:
  • fetch(req_or_url)

    该函数用于下载页面,可传入一个Request对象或一个url字符串,调用后更新request和response

  • view(response)

    该函数用于在浏览器中显示response所包含的页面

    分析页面数据

    接下来我们调用view()函数,在浏览器中显示response所包含的页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
In [1]: view(response)
Out[1]: True
# 首先用css定位到div.product_main目录
In [2]: rel = response.css('div.product_main')
# 其次用xpath定位到当前目录下的h1的文本信息
In [3]: rel.xpath('./h1/text()').extract_first()
# 根据你定义的规则返回值
Out[3]: 'A Light in the Attic'
In [4]: rel.xpath('./p[@class="price_color"]/text()').extract_first()
Out[4]: '£51.77'
# 注意正则表达式中star-rating后面有空格
# [A-Za-z]表示26个大小写英文字符过滤规则,[A-z]不仅包括了26个字符还包括[ \ ] ^ _ '这6个符号字符
In [5]: rel.css('p.star-rating::attr(class)').re_first('star-rating ([A-Za-z]+)')
Out[5]: 'Three'

分析页面链接

接下来分析如何在书籍列表中提取每一个书籍页面的链接,使用fetch()函数

1
2
3
4
5
In [1]: fetch('http://books.toscrape.com/')
2018-05-24 13:38:58 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://books.toscrape.com/> (referer: None)

In [2]: view(response)
Out[2]: True
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
# 导包
In [1]: from scrapy.linkextractors import LinkExtractor
# copy自chrome的开发者工具中的copy xpath,然后修改其中的li,将其[]删去
In [2]: le = LinkExtractor(restrict_xpaths='//*[@id="default"]/div/div/div/div/section/div[2]/ol/li/article')

In [3]: le.extract_links(response)
Out[3]:
[Link(url='http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/soumission_998/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/sharp-objects_997/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/the-requiem-red_995/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/the-dirty-little-secrets-of-getting-your-dream-job_994/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/the-coming-woman-a-novel-based-on-the-life-of-the-infamous-feminist-victoria-woodhull_993/index.html',text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/the-boys-in-the-boat-nine-americans-and-their-epic-quest-for-gold-at-the-1936-berlin-olympics_992/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/the-black-maria_991/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/starving-hearts-triangular-trade-trilogy-1_990/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/set-me-free_988/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/scott-pilgrims-precious-little-life-scott-pilgrim-1_987/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/rip-it-up-and-start-again_986/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/our-band-could-be-your-life-scenes-from-the-american-indie-underground-1981-1991_985/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/olio_984/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/mesaerion-the-best-science-fiction-stories-1800-1849_983/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/libertarianism-for-beginners_982/index.html', text='', fragment='', nofollow=False),
Link(url='http://books.toscrape.com/catalogue/its-only-the-himalayas_981/index.html', text='', fragment='', nofollow=False)]

编码实现

上面我们已经分析了这个页面我们所需要爬取的内容,获得了它对应的xpath或css,接下来我们要编码进行实现

  • 创建Scrapy项目
1
2
3
4
5
6
7
8
9
10
11
12
13
# 创建Scrapy项目
MacBook-Pro:~ mac $ scrapy startproject Second_book
New Scrapy project 'Second_book', using template directory '/Library/anaconda3/lib/python3.6/site-packages/scrapy/templates/project', created in:
/Users/mac/Second_book

You can start your first spider with:
cd Second_book
scrapy genspider example example.com
MacBook-Pro:~ mac$ cd Second_book/
# 使用scrapy genspider <Spider的名字><所需要爬取的网站>创建spider文件
MacBook-Pro:Second_book mintaoyu$ scrapy genspider books books.toscrape.com
Created spider 'books' using template 'basic' in module:
Second_book.spiders.books

我们可以在项目中看到已经创建好的books.py它为我们继承了scrapy.Spider类,为spider取了名,指定了爬取的起始地址,需要我们自己实现书籍列表页面和书籍页面的解析函数

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-
import scrapy


class BooksSpider(scrapy.Spider):
name = 'books'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/']

def parse(self, response):
pass
  • item.py中封装我们需要爬取的信息
1
2
3
4
5
6
7
8
class SecondBookItem(scrapy.Item):
name = Field() # 书名
price = Field() # 价格
review_rating = Field() # 评价等级
review_num = Field() # 评价数量
upc = Field() # 产品编码
stock = Field() # 库存量
pass

分析:我们爬取的页面是一个书籍列表页面,从该页面中我们可以获取每一本书籍的链接和下一页书籍列表页面的链接(NEXT)

books.py

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
33
34
35
36
37
38
39
40
41
42
43
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from ..items import SecondBookItem


class BooksSpider(scrapy.Spider):
name = 'books'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/']

# 书籍列表页面解析函数
def parse(self, response):
# 提取书籍列表页面中每本书的链接
le = LinkExtractor(restrict_xpaths='//article')
for link in le.extract_links(response):
yield scrapy.Request(link.url, callback=self.parse_book)
# 提取下一页
le = LinkExtractor(restrict_css='li.next')
# le = LinkExtractor(restrict_xpaths="//li[@class='next']")
links = le.extract_links(response)
if links:
next_url = links[0].url
yield scrapy.Request(next_url, callback=self.parse)

# 书籍页面解析函数
# 前面使用scrapy shell提取的信息放入xpath中
def parse_book(self, response):
book = SecondBookItem()
book['name'] = response.xpath(
"//div[contains(@class,'product_main')]/h1/text()").extract_first(
)
book['price'] = response.xpath(
"//p[@class='price_color']/text()").extract_first()
book['review_rating'] = response.xpath(
"//p[contains(@class,'star-rating')]").re_first(
'star-rating ([A-Za-z]+)')
book['stock'] = response.xpath(
# 正则表达式'\d+'代表匹配多个[0-9]的数字
"//p[@class='instock availability']/text()").re_first("\d+")
book['upc'] = response.xpath("//td/text()").extract_first()
book['review_num'] = response.xpath('//tr[7]/td/text()').extract_first()
yield book
赏个🍗吧
0%