[scrapy css选择器使用]http://www.scrapyd.cn/doc/146.html 理解
1. 学习之前,先看看shell调试----scrapy shell的调试使用
http://www.scrapyd.cn/doc/147.html
C:\Users\76147\PycharmProjects\mingyan>scrapy shell http://lab.scrapyd.cn
-------------------------------------------------------------------------------------------------------------------------------------------------------
2019-03-11 10:47:54 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: mingyan)
2019-03-11 10:47:54 [scrapy.utils.log] INFO: Versions: lxml 4.3.2.0, libxml2 2.9.5, cssselect 1.0.3, parsel 1.5.1, w3lib 1.20.0, Twist
ed 18.9.0, Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.0.0 (OpenSSL 1.1.1b
26 Feb 2019), cryptography 2.6.1, Platform Windows-10-10.0.17134-SP0
2019-03-11 10:47:54 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'mingyan', 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDu
peFilter', 'LOGSTATS_INTERVAL': 0, 'NEWSPIDER_MODULE': 'mingyan.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['mingyan.spiders'
]}
2019-03-11 10:47:54 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole']
2019-03-11 10:47:55 [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']
2019-03-11 10:47:55 [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']
2019-03-11 10:47:55 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2019-03-11 10:47:55 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2019-03-11 10:47:55 [scrapy.core.engine] INFO: Spider opened
2019-03-11 10:47:55 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://lab.scrapyd.cn/robots.txt> (referer: None)
2019-03-11 10:47:55 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://lab.scrapyd.cn> (referer: None)
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x000002482609CB70>
[s] item {}
[s] request <GET http://lab.scrapyd.cn>
[s] response <200 http://lab.scrapyd.cn>
[s] settings <scrapy.settings.Settings object at 0x000002482609CC50>
[s] spider <ExampleSpider 'example' at 0x24826346278>
[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
-------------------------------------------------------------------------------------------------------------------------------------------------------
>>> response.css('title')
[<Selector xpath='descendant-or-self::title' data='<title>SCRAPY爬虫实验室 - SCRAPY中文网提供</title>'>]
-------------------------------------------------------------------------------------------------------------------------------------------------------
>>> response.css('title')[0]
<Selector xpath='descendant-or-self::title' data='<title>SCRAPY爬虫实验室 - SCRAPY中文网提供</title>'>
-------------------------------------------------------------------------------------------------------------------------------------------------------
>>> response.css('title').extract()
['<title>SCRAPY爬虫实验室 - SCRAPY中文网提供</title>']
-------------------------------------------------------------------------------------------------------------------------------------------------------
>>> response.css('title').extract()[0]
'<title>SCRAPY爬虫实验室 - SCRAPY中文网提供</title>'
-------------------------------------------------------------------------------------------------------------------------------------------------------
>>> response.css('title').extract_first()
'<title>SCRAPY爬虫实验室 - SCRAPY中文网提供</title>'
SCRAPY爬虫实验室 - SCRAPY中文网提供
才是我们想要的,那么使用response.css(‘title::text’).extract_first()
extract_first()就代表提取第一个元素,和我们的:[0],一样的效果,只是更简洁些,至此我们已经成功提取到了我们的title,但是你会发现,肿么多了一个title标签,这并不是你需要的,那要肿么办呢,我们可以继续改变一下以上的输入:
>>> response.css('title::text').extract_first()
-------------------------------------------------------------------------------------------------------------------------------------------------------
'爬虫实验室 - SCRAPY中文网提供'
我们在title后面加上了 ::text ,这代表提取标签里面的数据,至此,我们已经成功提取到了我们需要的数据:
'爬虫实验室 - SCRAPY中文网提供'
-------------------------------------------------------------------------------------------------------------------------------------------------------
总结一下,其实就这么一段代码:
response.css('title::text').extract_first()
2. response.css(‘标签名’),标签名的话可以是html标签比如:title、body、div,也可以是你自定义的class标签
class = quote
>>> response.css('div.quote')
-------------------------------------------------------------------------------------------------------------------------------------------------------
[<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote post">\n\t
<span '>,
<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class),' '), ' quote ')]" data='<div class="quote post">\n\t
<span '>,
<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote post">\n\t
<span '>,
<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote post">\n\t
<span '>,
<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote post">\n\t
<span '>]
>>> response.css('div.quote')[0]
<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote post">\n\t <span '>
<div class="quote post">
<span class="text">看官,此页面只为爬虫练习使用,都是残卷,若喜欢可以去找点高清版!</span>
<span>作者:<small class="author">中国传世名画</small>
<a href="http://lab.scrapyd.cn/archives/57.html">【详情】</a>
</span>
<p></p>
<div class="tags">
标签: <a class='tag' href=http://lab.scrapyd.cn/tag/%E8%89%BA%E6%9C%AF/>艺术</a>,<a class='tag' href=http://lab.scrapyd.cn/tag/%E5%90%8D%E7%94%BB/>名画</a> </div>
</div>
3. class = text author tags 提取内容
>>> response.css('.text::text').extract_first()
'看官,此页面只为爬虫练习使用,都是残卷,若喜欢可以去找点高清版!'
**上面的表达式里面,我们使用了:.text 这是class选择器,如果是id选择器的话:#text**
4. 接下啦应用学习的内容,爬去一篇小说。
注意,只是用来学习,并无其他意思,如果,,,那啥,请联系删除
http://www.17k.com/chapter/1540808/22721472.html
class = readAreaBox
class = p
还有《001 归来》 < h1>
5. 源代码
# -*- coding: utf-8 -*-
import scrapy
class ItemSpider(scrapy.Spider):
name = 'itemSpider'
allowed_domains = ['lab.scrapyd.cn']
start_urls = ['http://www.17k.com/chapter/1540808/22721472.html']
def parse(self, response):
name = response.css('h1::text').extract_first()
name = name.replace("\n", ' ').strip()# h1标签内有一个换行符 还有很多空格
text = response.css('.readAreaBox .p::text').extract()
filename = '%s.txt' % name
with open(filename, 'a+') as f:
for i in text:
f.write(i)
f.close()