完成:抓取人人网上自己的blog文章

抓取人人日志

把自己的第一篇博客地址和Cookie保存到代码中,执行python renren_spider.py
即可

https://github.com/MioYvo/renren_blog_spider
附上代码

# coding=utf-8
# __author__ = 'Mio'

import requests
from bs4 import BeautifulSoup
from tornado.escape import utf8

download_dir = "/Users/mio/Downloads/renren_blog/"
first_url = "http://blog.renren.com/blog/408842825/938039669"
cookie = {"Cookie": " .... "}


def save_blog(blog_url):
    print blog_url
    html = requests.get(blog_url, cookies=cookie).content
    # soup = BeautifulSoup(open("/Users/mio/Desktop/r_blog.html"), "html.parser")
    soup = BeautifulSoup(html, "html.parser")

    # 日期
    blog_date = soup.find('span', class_="blogDetail-ownerOther-date")
    blog_date = utf8(blog_date.contents[0])
    # 标题
    title = soup.find('h2', class_="blogDetail-title")
    title = utf8(title.contents[0])
    title = title.replace("/", "\\")
    print title

    # print soup
    a = soup.find_all("div", class_="blogDetail-content")
    blog_content = a[0]

    with open("{}{}.md".format(download_dir, title), "wb") as fw:
        fw.write("# {}\n".format(title))
        fw.write("> {}\n\n".format(blog_date))
        for i in blog_content:
            try:
                fw.write(str(i))
            except Exception as e:
                print e
                pass

    return get_next(soup)


def get_next(soup):
    # 下一篇
    pre_and_next = soup.find_all(class_="blogDetail-pre")
    if pre_and_next:
        next_blog_url = pre_and_next[0].findAll('a', href=True)
        if next_blog_url:
            return next_blog_url[0]['href']
    return False

if __name__ == '__main__':
    while True:
        next_url = save_blog(first_url)
        if next_url:
            url = next_url
        else:
            print 'done'
            break

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.AOP的基本概念 (1)Aspect(切面):通常是一个类,里面可以定义切入点和通知 (2)JointPoin...
    我是java程序员阅读 370评论 0 0
  • 深知自己能力不够,却没有什么能力改变。或许可以改变,但是不愿意改变。看狐妖看了许久,深深陷入其中不能自拔。为什么呢...
    缉熙_f30d阅读 273评论 0 0
  • “生活不止眼前的苟且,还有诗和远方的田野,你赤手空拳来到这人间,为找到那片海不顾一切。”——高晓松 这是一声曾让无...
    我从未见过你阅读 356评论 0 3