美文网首页
使用 Python 爬取简书网的所有文章

使用 Python 爬取简书网的所有文章

作者: AirPython | 来源:发表于2018-12-17 21:01 被阅读23次
    image

    阅读文本大概需要 6 分钟。

    抓取目标

    我们要爬取的目标是「 简书网 」。

    打开简书网的首页,随手点击一篇文章进入到详情页面。

    image

    我们要爬取的数据有:作者、头像、发布时间、文章 ID 以及文章内容

    准备工作

    在编写爬虫程序之前,我都是先对页面进行简单分析,然后指定爬取思路。

    由于我们爬取简书网所有的文章数据,所以考虑使用「 CrawlSpider 」来对整个网站进行爬取。

    首先使用 Scrapy 创建一个项目和一个爬虫

    # 打开 CMD 或者终端到一个指定目录
    # 新建一个项目
    scrapy startproject jianshu_spider
    
    cd jianshu_spider
    
    # 创建一个爬虫
    scrapy genspider -t crawl jianshu "jianshu.com"
    

    爬取的数据准备存储到 Mysql 数据库中,因此需要提前建立好数据库和表。

    image

    爬取思路

    首先,我们我们检查首页页面文章列表每一项的 href 属性、文章详情页面的地址、详情页面推荐文章中的 href 属性。

    image image image

    可以获取出规律,每一篇文章的地址,即 URL 是由「.../p/文章id/... 」构成,其中文章 ID 是由小写字母 a-z 或者 0-9 的 12 位数字构成,因此 Rule 构成如下:

    /p/[0-9a-z]{12}
    

    代码实现

    第一步是指定开始爬取的地址和爬取规则。

    allowed_domains = ['jianshu.com'] 
    start_urls = ['https://www.jianshu.com/']   
    rules = (        
    # 文章id是有12位小写字母或者数字0-9构成        
    Rule(LinkExtractor(allow=r'.*/p/[0-9a-z]{12}.*'), callback='parse_detail', follow=True),    )
    

    第二步是拿到下载器下载后的数据 Response,利用 Xpath 语法获取有用的数据。这里可以使用「 Scrapy shell url 」去测试数据是否获取正确。

     # 获取需要的数据 
    title = response.xpath('//h1[@class="title"]/text()').get() 
    author = response.xpath('//div[@class="info"]/span/a/text()').get() 
    avatar = self.HTTPS + response.xpath('//div[@class="author"]/a/img/@src').get() 
    pub_time = response.xpath('//span[@class="publish-time"]/text()').get().replace("*", "") 
    current_url = response.url 
    real_url = current_url.split(r"?")[0] 
    article_id = real_url.split(r'/')[-1] 
    content = response.xpath('//div[@class="show-content"]').get()
    

    然后构建 Item 模型用来保存数据。

    import scrapy
    # 文章详情Itemclass ArticleItem(scrapy.Item):    
    title = scrapy.Field()    
    content = scrapy.Field()    
    # 文章id   
    article_id = scrapy.Field()   
    # 原始的url  
    origin_url = scrapy.Field()    
    # 作者    
    author = scrapy.Field()    
    # 头像    
    avatar = scrapy.Field()    
    # 发布时间    
    pubtime = scrapy.Field()
    

    第三步是将获取的数据通过 Pipline 保存到数据库中。

    # 数据库连接属性
    db_params = {            
    'host': '127.0.0.1',            
    'port': 3306,            
    'user': 'root',          
    'password': 'root',          
    'database': 'jianshu',          
    'charset': 'utf8'
    }
    # 数据库【连接对象】
    self.conn = pymysql.connect(**db_params)
    # 构建游标对象self.cursor = self.conn.cursor()
    # sql 插入语句self._sql = """          insert into article(id,title,content,author,avatar,pubtime,article_id,origin_url)         values(null,%s,%s,%s,%s,%s,%s,%s)"""
    
    # 执行 sql 语句
    self.cursor.execute(self._sql, ( item['title'], item['content'], item['author'], item['avatar'], item['pubtime'], item['article_id'], item['origin_url']))
    # 插入到数据库中
    self.conn.commit()
    # 关闭游标资源
    self.cursor.close()
    

    爬取结果

    执行命令「 scrapy crawl jianshu」 运行爬虫程序。

    注意设置 settings.py 中延迟 DOWNLOAD_DELAY和管道ITEM_PIPELINES 保证数据能正常写入到数据库中。

    最后查看数据库,发现数据能正常写入到表中。

    image

    本文首发于公众号「 AirPython 」,后台回复「简书」即可获取完整代码。

    相关文章

      网友评论

          本文标题:使用 Python 爬取简书网的所有文章

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