python实现博客文章爬虫示例

yipeiwu_com5年前Python爬虫

复制代码 代码如下:

#!/usr/bin/python
#-*-coding:utf-8-*-
# JCrawler
# Author: Jam <810441377@qq.com>

import time
import urllib2
from bs4 import BeautifulSoup

# 目标站点
TargetHost = "http://adirectory.blog.com"
# User Agent
UserAgent  = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'
# 链接采集规则
# 目录链接采集规则
CategoryFind    = [{'findMode':'find','findTag':'div','rule':{'id':'cat-nav'}},
                   {'findMode':'findAll','findTag':'a','rule':{}}]
# 文章链接采集规则
ArticleListFind = [{'findMode':'find','findTag':'div','rule':{'id':'content'}},
                   {'findMode':'findAll','findTag':'h2','rule':{'class':'title'}},
                   {'findMode':'findAll','findTag':'a','rule':{}}]
# 分页URL规则
PageUrl  = 'page/#page/'
PageStart = 1
PageStep  = 1
PageStopHtml = '404: Page Not Found'

def GetHtmlText(url):
    request  = urllib2.Request(url)
    request.add_header('Accept', "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp")
    request.add_header('Accept-Encoding', "*")
    request.add_header('User-Agent', UserAgent)
    return urllib2.urlopen(request).read()

def ArrToStr(varArr):
    returnStr = ""
    for s in varArr:
        returnStr += str(s)
    return returnStr


def GetHtmlFind(htmltext, findRule):
    findReturn = BeautifulSoup(htmltext)
    returnText = ""
    for f in findRule:
        if returnText != "":
            findReturn = BeautifulSoup(returnText)
        if f['findMode'] == 'find':
            findReturn = findReturn.find(f['findTag'], f['rule'])
        if f['findMode'] == 'findAll':
            findReturn = findReturn.findAll(f['findTag'], f['rule'])
        returnText = ArrToStr(findReturn)
    return findReturn

def GetCategory():
    categorys = [];
    htmltext = GetHtmlText(TargetHost)
    findReturn = GetHtmlFind(htmltext, CategoryFind)

    for tag in findReturn:
        print "[G]->Category:" + tag.string + "|Url:" + tag['href']
        categorys.append({'name': tag.string, 'url': tag['href']})
    return categorys;

def GetArticleList(categoryUrl):
    articles = []
    page = PageStart
    #pageUrl = PageUrl
    while True:
        htmltext = ""
        pageUrl  = PageUrl.replace("#page", str(page))
        print "[G]->PageUrl:" + categoryUrl + pageUrl
        while True:
            try:
                htmltext = GetHtmlText(categoryUrl + pageUrl)
                break
            except urllib2.HTTPError,e:
                print "[E]->HTTP Error:" + str(e.code)
                if e.code == 404:
                    htmltext = PageStopHtml
                    break
                if e.code == 504:
                    print "[E]->HTTP Error 504: Gateway Time-out, Wait"
                    time.sleep(5)
                else:
                    break

        if htmltext.find(PageStopHtml) >= 0:
            print "End Page."
            break
        else:

            findReturn = GetHtmlFind(htmltext, ArticleListFind)

            for tag in findReturn:
                if tag.string != None and tag['href'].find(TargetHost) >= 0:
                    print "[G]->Article:" + tag.string + "|Url:" + tag['href']
                    articles.append({'name': tag.string, 'url': tag['href']})

            page += 1

    return articles;

print "[G]->GetCategory"
Mycategorys = GetCategory();
print "[G]->GetCategory->Success."
time.sleep(3)
for category in Mycategorys:
   print "[G]->GetArticleList:" + category['name']
   GetArticleList(category['url'])

相关文章

Python爬虫之模拟知乎登录的方法教程

Python爬虫之模拟知乎登录的方法教程

前言 对于经常写爬虫的大家都知道,有些页面在登录之前是被禁止抓取的,比如知乎的话题页面就要求用户登录才能访问,而 “登录” 离不开 HTTP 中的 Cookie 技术。 登录原理 Coo...

基于Python的Post请求数据爬取的方法详解

为什么做这个 和同学聊天,他想爬取一个网站的post请求 观察 该网站的post请求参数有两种类型:(1)参数体放在了query中,即url拼接参数(2)body中要加入一个空的json...

python爬虫神器Pyppeteer入门及使用

python爬虫神器Pyppeteer入门及使用

前言 提起selenium想必大家都不陌生,作为一款知名的Web自动化测试框架,selenium支持多款主流浏览器,提供了功能丰富的API接口,经常被我们用作爬虫工具来使用。但是sele...

python urllib爬取百度云连接的实例代码

python urllib爬取百度云连接的实例代码

翻看自己以前写的程序,发现写过一个爬取盘多多百度云资源的东西,完全是当时想看变形金刚才自己写的,而且当时第一次接触python大概写了有2天才搞出来这个程序,学习python语言,可以看...

python抓取最新博客内容并生成Rss

osc的rss不是全文输出的,不开心,所以就有了python抓取osc最新博客生成Rss # -*- coding: utf-8 -*- from bs4 import Beau...