python爬去知乎和简书内容

原创 2017年09月10日 21:42:28

 一、爬取知乎热门内容

# -*- coding: utf-8-*-
import urllib2
import re
from BeautifulSoup import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf8')

f = open('howtoTucao2.txt', 'w')  # open the file

for pagenum in range(1, 21):

    strpagenum = str(pagenum)
    print "Getting data for Page " + strpagenum  # for we can see the process in shell
    url = "http://www.zhihu.com/collection/27109279?page=" + strpagenum
    page = urllib2.urlopen(url)  # get the web page
    soup = BeautifulSoup(page)  # use BeautifulSoup to parsing the web page

    ALL = soup.findAll(attrs={'class': ['zm-item-title', 'content hidden']})

    for each in ALL:
        if each.name == 'h2':
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n', '', each.a.string)
            nowstring = re.sub('<br>', '\n', nowstring)
            nowstring = re.sub('<\w+>', '', nowstring)
            nowstring = re.sub('</\w+>', '', nowstring)
            nowstring = re.sub('<.+>', '\n图片\n', nowstring)
            nowstring = re.sub('"', '"', nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else:
                f.write("\n No Answer \n")
        else:
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n', '', each.string)
            nowstring = re.sub('<br>', '\n', nowstring)
            nowstring = re.sub('<\w+>', '', nowstring)
            nowstring = re.sub('</\w+>', '', nowstring)
            nowstring = re.sub('<.+>', '\n图片\n', nowstring)
            nowstring = re.sub('"', '"', nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else:
                f.write("\n No Answer \n")
f.close()  # close the file


二、爬取简书内容(基于Scrapy框架)

 (1)item.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy
'''
作者名称
作者的头像
文章标题
文章链接
文章描述
文章内容
文章阅读量
评论量
喜欢的人数及赞赏的人数
'''

class ArticleItem(scrapy.Item):
    # define the fields for your item here like:
    author_name = scrapy.Field()
    author_image = scrapy.Field()
    article_release_time = scrapy.Field()
    article_title = scrapy.Field()
    article_desc = scrapy.Field()
    #article_content=scrapy.Field()
    article_link = scrapy.Field()
    read_count = scrapy.Field()
    reply_count = scrapy.Field()
    likeit_count = scrapy.Field()
    payit_count = scrapy.Field()

  (2)pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
import pymongo

class JsonWriterJianshuPipeline(object):
    
    def __init__(self):
        self.file = codecs.open('jianshu_data_utf-8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(line)
        return item

    def spider_closed(self, spider):
        self.file.close()


class MongoJianshuPipeline(object):
    # 定义数据表的名称
    collection_name = 'jianshu_member_article'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        self.db[self.collection_name].insert(dict(item))
        return item
 (3)jianshuspider.py

# -*- coding: utf-8 -*-
import scrapy
from jianshu.items import ArticleItem

class JsmemberspiderSpider(scrapy.Spider):
    name = "jsMemberSpider"
    # allowed_domains = ["jianshu"]
    jianshu = 'http://www.jianshu.com'
    start_urls = ['http://www.jianshu.com/u/54b5900965ea?order_by=shared_at&page=1', ]
    
    article_all = []

    start_url = 'http://www.jianshu.com/u/54b5900965ea?order_by=shared_at&page={}'
    start_page = 1
    userID = '54b5900965ea'
    pageNumber = 1
    stop_url = 'http://www.jianshu.com/u/{USERID}?order_by=shared_at&page={pageNumber}'.format(USERID = userID, pageNumber = pageNumber)

    def parse(self, response):
        # 获取文章总数
        article_count = response.css(
            'body > div.container.person > div > div.col-xs-16.main > div.main-top > div.info > ul > li:nth-child(3) > div > a > p::text').extract_first()
        # 计算共分了多少页,每页9篇文章
        countPageNumber = int(int(article_count) / 9 + 0.5)
        # 获取文章列表
        articles = response.css('ul.note-list > li')
        for article in articles:
            articleItem = ArticleItem()
            # 获取作者名称
            articleItem['author_name'] = article.css('a.blue-link::text').extract_first()
            # author_name = article.css('a.blue-link::text').extract_first()
            # 获取作者的头像连接
            articleItem['author_image'] = 'http:' + article.css('div.author > a > img::attr(src)').extract_first()
            # author_image = 'http:' + article.css('div.author > a > img::attr(src)').extract_first()
            # 获取文章发布时间
            articleItem['article_release_time'] = article.css('div.name > span.time::attr(data-shared-at)').extract_first()
            article_release_time = article.css('div.name > span.time::attr(data-shared-at)').extract_first()
            # 获取标题
            articleItem['article_title'] = article.css('a.title::text').extract_first()
            # article_title = article.css('a.title::text').extract_first()
            # 获取文章描述 
            articleItem['article_desc'] = article.css('p.abstract::text').extract_first().strip()
            # 获取文章的内容
            #articleItem['article_content'] = article.css('p.abstract::text').extract_first().strip()
            # 获取文章链接
            articleItem['article_link'] = JsmemberspiderSpider.jianshu + article.css('div.content > a::attr(href)').extract_first()
            # article_link = JsmemberspiderSpider.jianshu + article.css('div.content > a::attr(href)').extract_first()
            # 获取阅读量,回复量,喜欢人数,赞赏人数
            articleItem['read_count'] = article.css('div.meta > a')[0].css('::text').extract()[-1].strip()
            articleItem['reply_count'] = article.css('div.meta > a')[1].css('::text').extract()[-1].strip()
            articleItem['likeit_count'] = article.css('div.meta > span')[0].css('::text').extract_first().strip()
            articleItem['payit_count'] = article.css('div.meta > span')[1].css('::text').extract_first().strip() if len(article.css('div.meta > span'))>=2 else 0
            JsmemberspiderSpider.article_all.append(articleItem)
            yield articleItem
            # pages = (i for i in range(2, countPageNumber + 1))
            current_page = int(response.url.split('page=')[1])
            next_page = JsmemberspiderSpider.start_url.format(current_page + 1)
            # 爬虫结束的条件,如果当前页是最后一页
            if current_page == countPageNumber:
                next_page = None
            if next_page is not None:
                next_page = response.urljoin(next_page)
                # yield {
                # '爬取中:': next_page,
                # }
                yield scrapy.Request(next_page, callback=self.parse)

(4)settings.py

# -*- coding: utf-8 -*-

# Scrapy settings for jianshu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'jianshu'

SPIDER_MODULES = ['jianshu.spiders']
NEWSPIDER_MODULE = 'jianshu.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'jianshu (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'Accept-Language': 'en',
  'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'jianshu.middlewares.JianshuSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'jianshu.middlewares.MyCustomDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'jianshu.pipelines.JsonWriterJianshuPipeline': 300,
   #'jianshu.pipelines.MongoJianshuPipeline': 800,
}

# Configure PyMongo
MONGO_URI = 'mongodb://localhost:27017/'
# 数据库名称
MONGO_DATABASE = 'jianshu'

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

(5)运行 scrapy   crawl  jsMemberSpider





版权声明:本文为博主原创文章,未经博主允许不得转载。

Python抓取简书的热门文章

原理和上章获取段子一样,只不过是换了解析的内容。 代码: #-*- coding: utf-8 -*- import urllib2 import re def GetPageContent(p...
  • u014161864
  • u014161864
  • 2015年05月24日 23:37
  • 1473

简书爬取专题文章(爱它就把它爬下来)

简书里的文章有分专题,如 然后随便进入一个专题: 然后问题来,这个专题里面总共有132篇文章,但是先看看它的源代码,里面的有一篇文章居然在源码里搜不到!这也就意味着这篇文章的链接就提取不到...
  • sinat_33455447
  • sinat_33455447
  • 2016年07月15日 17:28
  • 825

个人技术博客的选择:CSDN、博客园、简书、知乎专栏还是Github Page?

有很多技术人员在学习到一定程度后发现了写博客的重要性,一方面帮助自己记忆,一方面也能帮助他人解决问题,于是会选择自己开始写博客,之后又发现平台太多不知从何下手,在这里我根据自己写博客的经验比较一下各个...
  • grape875499765
  • grape875499765
  • 2018年01月09日 21:51
  • 2313

python爬虫 爬取知乎用户的用户信息

我用python爬虫找到了不想告诉我她知乎ID的妹纸的ID…….在我做了这件事情之后 , 她觉得我越来越懂她了 , 嘻嘻有一天 , 我发现我心仪已久的妹纸在朋友圈里分享了知乎专栏的文章 , 就知道她也...
  • qq_21970857
  • qq_21970857
  • 2015年06月17日 18:43
  • 2529

Python网络爬虫对知乎首页进行爬取

# -*- coding: UTF-8 -*- import urllib, urllib2, cookielib, re, time, os import requests print 'zh...
  • u012599619
  • u012599619
  • 2015年07月15日 11:57
  • 1454

Python爬虫爬取知乎小结

博客首发至Marcovaldo’s blog (http://marcovaldong.github.io/)最近学习了一点网络爬虫,并实现了使用python来爬取知乎的一些功能,这里做一个小的总结。...
  • MajorDong100
  • MajorDong100
  • 2016年08月20日 23:03
  • 15711

python爬虫实战之爬取知乎帖子

刚开始学习python爬虫,参考代码:https://github.com/lijaha/web-spider/blob/master/Get_ZhiHu_question.py  相关教程http...
  • caduca
  • caduca
  • 2015年12月16日 20:57
  • 6518

Python写的爬取知乎的最多一百篇文章

这几天经常上知乎,觉得里面有些
  • castle07
  • castle07
  • 2014年07月15日 14:16
  • 987

python爬虫——爬取知乎上自己关注的问题

与之前爬的网站图片的不同的是,现在爬取的是要自己个人的关注的东西,所以需要做到模拟登录。模拟登录的原理是登录网站后,在浏览器上获取保存的cookies信息,填充之后与请求一起发送。...
  • iaiti
  • iaiti
  • 2015年11月27日 11:24
  • 6578

通过Python爬虫爬取知乎某个问题下的图片

该爬虫主要是通过requests来实现的,该模块完全可以很好的代替urllib和urllib2,而且功能更强大,详细可以看这里。同时也用到了pillow模块中的image对象,实现环境是Python2...
  • Enter_
  • Enter_
  • 2016年07月10日 21:36
  • 15050
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:python爬去知乎和简书内容
举报原因:
原因补充:

(最多只允许输入30个字)