CONTENTS
参考链接
【 https://juejin.im/post/5cfc6f716fb9a07ea7130308 】
【 https://segmentfault.com/a/1190000013178839 】
【 https://scrapy-chs.readthedocs.io/zh_CN/latest/index.html 】
scrapy是一个非常强大的爬虫框架,这里就简单的笔记下如何使用,详细使用可以查考doc。
以爬取本博客为例,
文件方式
####bloglist_spider.py import scrapy class bloglist_spider(scrapy.Spider): name = 'bloglist' allowed_domains = ['cstriker1407.info'] start_urls = ['http://cstriker1407.info/blog'] def parse(self, response): for single_post in response.xpath("//div[@class='post-header']"): print("publish_title:" + single_post.xpath("h2/a/text()").extract()[0] ) print("publish_time:" + single_post.xpath("p[2]/a[1]/text()").extract()[0])
命令执行结果如下:
#scrapy crawl bloglist 。。。。。。。 。。。。。。。 publish_title:VisualStudio编译环境的选择 publish_time:2020年6月28日 publish_title:【转】Cortex-M3的工作模式和特权级别 publish_time:2020年6月17日 publish_title:GCC安全编译选项 。。。。。。。 。。。。。。。
shell方式
# scrapy shell http://cstriker1407.info/blog 。。。。。。 。。。。。。 [s] Available Scrapy objects: [s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc) [s] crawler <scrapy.crawler.Crawler object at 0x000001F900C71D08> [s] item {} [s] request <GET http://cstriker1407.info/blog> [s] response <200 https://cstriker1407.info/blog/> [s] settings <scrapy.settings.Settings object at 0x000001F900C71C08> [s] spider <bloglist_spider 'bloglist' at 0x1f900ffcf48> [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.xpath("//div[@class='post-header']").extract() ['<div"> 。。。。。。。 。。。。。。。</div>'] >>> response.xpath("//div[@class='post-header']")[0].extract() '<div class="post-header">\n\t\t\t\t\t\t\t\n\t\t\t\t\t<p class="post-categories"><a href="https://cstriker1407.info/blog/category/coding/c-cplusplus/" rel="category tag">C && C++</a>, <a href="https://cstriker1407.info/blog/category/operationsystem/windows-ops/" rel="category tag">windows</a>, <a href="https://cstriker1407.info/blog/category/coding/" rel="category tag">编程</a></p>\n\t\t\t\t\n\t\t\t\t\t\n\t\t <h2 class="post-title"><a href="https://cstriker1407.info/blog/build-env-in-vs/">VisualStudio编译环境的选择</a></h2>\n\t\t \n\t\t\t\t\n\t\t<p class="post-meta">\n\t\t\t<a href="https://cstriker1407.info/blog/build-env-in-vs/">2020年6月28日</a> \n\t\t\t — <a href="https://cstriker1407.info/blog/build-env-in-vs/#respond">0 Comments</a>\t\t</p>\n\t\t\n\t</div>' >>> response.xpath("//div[@class='post-header']")[0].xpath("h2/a/text()").extract() ['VisualStudio编译环境的选择'] >>> response.xpath("//div[@class='post-header']")[0].xpath("p[2]/a[1]/text()").extract() ['2020年6月28日'] >>> response.xpath("//div[@class='post-header']")[0].xpath("p[2]/a[1]/text()").extract()[0] '2020年6月28日'
发表评论