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 爬虫之Beautiful Soup模块使用指南

爬取网页的流程一般如下: 选着要爬的网址(url) 使用 python 登录上这个网址(urlopen、requests 等) 读取网页信息(read() 出来) 将读...

基于python 爬虫爬到含空格的url的处理方法

道友问我的一个问题,之前确实没遇见过,在此记录一下。 问题描述 在某网站主页提取url进行迭代,爬虫请求主页时没有问题,返回正常,但是在访问在主页提取到的url时出现了400状态码(40...

利用selenium爬虫抓取数据的基础教程

写在前面 本来这篇文章该几个月前写的,后来忙着忙着就给忘记了。 ps:事多有时候反倒会耽误事。 几个月前,记得群里一朋友说想用selenium去爬数据,关于爬数据,一般是模拟访问某...

Python实现抓取网页生成Excel文件的方法示例

本文实例讲述了Python实现抓取网页生成Excel文件的方法。分享给大家供大家参考,具体如下: Python抓网页,主要用到了PyQuery,这个跟jQuery用法一样,超级给力 示例...

Python3 实现爬取网站下所有URL方式

获取首页元素信息: 目标 test_URL:http://www.xxx.com.cn/ 首先检查元素,a 标签下是我们需要爬取得链接,通过获取链接路径,定位出我们需要的信息 sou...