美文网首页菜鸟Python 爬虫专栏程序员
专栏:015:重构“你要的实战篇"

专栏:015:重构“你要的实战篇"

作者: 谢小路 | 来源:发表于2016-05-14 22:20 被阅读351次

用理工科思维看待这个世界

系列爬虫专栏

初学者,尽力实现最小化学习系统

**主题:重构专栏:014 + Scrapy 实战 + sqlalchemy **

0:目标说明

  • Scrapy 基础教程
    你要的最佳实战

  • 刘未鹏博客
    点我啊

  • 目标:获取刘未鹏博客全站博文

    • 文章标题:Title
    • 文章发布时间:Time
    • 文章全文:Content
    • 文章的链接:Url
  • 思路:

    • 分析首页和翻页的组成
    • 抓取全部的文章链接
    • 在获取的全部链接的基础上解析需要的标题,发布时间,全文和链接

之前的逻辑是starts_url 包括全部的1,2,3,4页,在这个的基础上进行提取各个网页的文章的所需字段。

scrapy 可以编写Rule 规则抓取需要的url


1:目标分解

编写的规则:

start_urls = ["http://mindhacks.cn/"]
rules = (Rule(SgmlLinkExtractor(allow=(r'http://mindhacks.cn/page/\d+/',))),
         Rule(SgmlLinkExtractor(allow=(r'http://mindhacks.cn/\d{4,}/\d{2,}/\d{2,}/.*?-.*?-.*?-.*?/')), callback='parse_detail', follow = True)
         )
# 前一个Rule获取的是1,2,3,4页的网页组成: 如:http://mindhacks.cn/page/2/
# 后一个Rule获取的1,2,3,4网页下符合要求的文章的链接, 再在获取的文章链接的基础上进行解析 如:http://mindhacks.cn/2009/07/06/why-you-should-do-it-yourself/

解析文本函数:

def parse_detail(self, response):
   Item = LiuweipengItem()
   selector = Selector(response)
   title = selector.xpath('//div[@id="content"]/div/h1[@class="entry-title"]/a/text()').extract()
   time = selector.xpath('//div[@id="content"]/div/div[@class="entry-info"]/abbr/text()').extract()
   content = selector.xpath('//div[@id="content"]/div/div[@class="entry-content clearfix"]/p/text()').extract()
   url = selector.xpath('//div[@id="content"]/div/h1[@class="entry-title"]/a/@href').extract()
   for title, time, content, url in zip(title, time, content, url):
       Item["Title"] = title
       Item["Time"] = time
       Item["Content"] = content
       Item["Url"] = url
   yield Item
# 返回的Item 是需要抓取字段

2:ORM

参见:专栏:012

数据表声明

from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Article(Base):
    __tablename__ = "article"
    id = Column(Integer, primary_key=True)
    Title = Column(String)
    Time = Column(String)
    Content = Column(String)
    Url = Column(String)



3:储存

再次说明scrapy 文件目录结构和作用:

  • items.py : 抓取的目标,定义数据结构
  • pipelines.py : 处理数据
  • settings.py : 设置文件,常量等设置
  • spiders/: 爬虫代码

所以储存操作:pipelines.py
需要在本地先创建数据库表:

CREATE TABLE `article` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `Title` VARCHAR(255) COLLATE utf8_bin NOT NULL,
  `Content` VARCHAR(255) COLLATE utf8_bin NOT NULL,
  `Time` VARCHAR(255) COLLATE utf8_bin NOT NULL,
  `Url` VARCHAR(255) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

def open_spider(self, spider):
    engine = create_engine("mysql://root:123456@localhost:3306/test?charset=utf8", echo = True)
    DBSession = sessionmaker(bind=engine)
    self.session = DBSession()
    pass

def process_item(self, item, spider):
    one = Article(Title=item["Title"],
                Time=item["Time"],
                Content=item["Content"],
                Url=item["Url"])
    self.session.add(one)

    pass
def close_spider(self, spider):
    self.session.commit()
    self.session.close()
    pass

效果显示:

1463234534713.png
  • Tips

IDE下启动scrapy 爬虫:

新建任意一个文件:比如:main.py

# 文件中添加如下代码
from scrapy.cmdline import execute
execute("scrapy crawl name".split())

运行这个文件,就可以启动爬虫,其中name , 是spiders文件下编写爬虫所对应的那个name

完整代码: 点不点都是代码


4:总结和说明

参考文献:
强烈建议:1
强烈建议:2

Scrapy 爬虫框架还存在许多的未知...

Scrapy各种实例

任何实用性的东西都解决不了你所面临的实际问题,但为什么还有看?为了经验,为了通过阅读抓取别人的经验,虽然还需批判思维看待

相关文章

网友评论

    本文标题:专栏:015:重构“你要的实战篇"

    本文链接:https://www.haomeiwen.com/subject/vicvrttx.html