Python爬取读者并制作成PDF


Posted in Python onMarch 10, 2015

学了下beautifulsoup后,做个个网络爬虫,爬取读者杂志并用reportlab制作成pdf..

crawler.py

#!/usr/bin/env python

#coding=utf-8

"""

    Author:         Anemone

    Filename:       getmain.py

    Last modified:  2015-02-19 16:47

    E-mail:         anemone@82flex.com

"""

import urllib2

from bs4 import BeautifulSoup

import re

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

def getEachArticle(url):

#    response = urllib2.urlopen('http://www.52duzhe.com/2015_01/duzh20150104.html')

    response = urllib2.urlopen(url)

    html = response.read()

    soup = BeautifulSoup(html)#.decode("utf-8").encode("gbk"))

    #for i in soup.find_all('div'):

    #    print i,1

    title=soup.find("h1").string

    writer=soup.find(id="pub_date").string.strip()

    _from=soup.find(id="media_name").string.strip()

    text=soup.get_text()#.encode("utf-8")

    main=re.split("BAIDU_CLB.*;",text)

    result={"title":title,"writer":writer,"from":_from,"context":main[1]}

    return result

    #new=open("new.txt","w")

    #new.write(result["title"]+"\n\n")

    #new.write(result["writer"]+"  "+result["from"])

    #new.write(result["context"])

    #new.close()

def getCatalog(issue):

    url="http://www.52duzhe.com/"+issue[:4]+"_"+issue[-2:]+"/"

    firstUrl=url+"duzh"+issue+"01.html"

    firstUrl=url+"index.html"

    duzhe=dict()

    response = urllib2.urlopen(firstUrl)

    html = response.read()

    soup=BeautifulSoup(html)

    firstUrl=url+soup.table.a.get("href")

    response = urllib2.urlopen(firstUrl)

    html = response.read()

    soup = BeautifulSoup(html)

    all=soup.find_all("h2")

    for i in all:

        print i.string

        duzhe[i.string]=list()

        for link in i.parent.find_all("a"):

            href=url+link.get("href")

            print href

            while 1:

                try:

                    article=getEachArticle(href)

                    break

                except:

                    continue

            duzhe[i.string].append(article)

    return duzhe

def readDuZhe(duzhe):

    for eachColumn in duzhe:

        for eachArticle in duzhe[eachColumn]:

            print eachArticle["title"]

if __name__ == '__main__':

#    issue=raw_input("issue(201501):")

    readDuZhe(getCatalog("201424"))

getpdf.py

#!/usr/bin/env python

#coding=utf-8

"""

    Author:         Anemone

    Filename:       writetopdf.py

    Last modified:  2015-02-20 19:19

    E-mail:         anemone@82flex.com

"""

#coding=utf-8

import reportlab.rl_config

from reportlab.pdfbase import pdfmetrics

from reportlab.pdfbase.ttfonts import TTFont

from reportlab.lib import fonts

import copy

from reportlab.platypus import Paragraph, SimpleDocTemplate,flowables

from reportlab.lib.styles import getSampleStyleSheet

import crawler

def writePDF(issue,duzhe):

    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    pdfmetrics.registerFont(TTFont('song',"simsun.ttc"))

    pdfmetrics.registerFont(TTFont('hei',"msyh.ttc"))

    fonts.addMapping('song', 0, 0, 'song')

    fonts.addMapping('song', 0, 1, 'song')

    fonts.addMapping('song', 1, 0, 'hei')

    fonts.addMapping('song', 1, 1, 'hei')

    stylesheet=getSampleStyleSheet()

    normalStyle = copy.deepcopy(stylesheet['Normal'])

    normalStyle.fontName ='song'

    normalStyle.fontSize = 11

    normalStyle.leading = 11

    normalStyle.firstLineIndent = 20

    titleStyle = copy.deepcopy(stylesheet['Normal'])

    titleStyle.fontName ='song'

    titleStyle.fontSize = 15

    titleStyle.leading = 20

    firstTitleStyle = copy.deepcopy(stylesheet['Normal'])

    firstTitleStyle.fontName ='song'

    firstTitleStyle.fontSize = 20

    firstTitleStyle.leading = 20

    firstTitleStyle.firstLineIndent = 50

    smallStyle = copy.deepcopy(stylesheet['Normal'])

    smallStyle.fontName ='song'

    smallStyle.fontSize = 8

    smallStyle.leading = 8

    story = []

    story.append(Paragraph("<b>读者{0}期</b>".format(issue), firstTitleStyle))

    for eachColumn in duzhe:

        story.append(Paragraph('__'*28, titleStyle))

        story.append(Paragraph('<b>{0}</b>'.format(eachColumn), titleStyle))

        for eachArticle in duzhe[eachColumn]:

            story.append(Paragraph(eachArticle["title"],normalStyle))

    story.append(flowables.PageBreak())

    for eachColumn in duzhe:

        for eachArticle in duzhe[eachColumn]:

            story.append(Paragraph("<b>{0}</b>".format(eachArticle["title"]),titleStyle))

            story.append(Paragraph(" {0}  {1}".format(eachArticle["writer"],eachArticle["from"]),smallStyle))

            para=eachArticle["context"].split("")

            for eachPara in para:

                story.append(Paragraph(eachPara,normalStyle))

            story.append(flowables.PageBreak())

    #story.append(Paragraph("context",normalStyle))

    doc = SimpleDocTemplate("duzhe"+issue+".pdf")

    print "Writing PDF..."

    doc.build(story)

def main(issue):

    duzhe=crawler.getCatalog(issue)

    writePDF(issue,duzhe)

if __name__ == '__main__':

    issue=raw_input("Enter issue(201501):")

    main(issue)

以上就是本文的全部内容了,希望大家能够喜欢。

Python 相关文章推荐
Python多进程编程技术实例分析
Sep 16 Python
进一步理解Python中的函数编程
Apr 13 Python
python中import reload __import__的区别详解
Oct 16 Python
Python数据分析之双色球中蓝红球分析统计示例
Feb 03 Python
python opencv之分水岭算法示例
Feb 24 Python
Python中py文件引用另一个py文件变量的方法
Apr 29 Python
将Django项目部署到CentOs服务器中
Oct 18 Python
Python绘制股票移动均线的实例
Aug 24 Python
Win10下安装并使用tensorflow-gpu1.8.0+python3.6全过程分析(显卡MX250+CUDA9.0+cudnn)
Feb 17 Python
Python 实现平台类游戏添加跳跃功能
Mar 27 Python
对python中各个response的使用说明
Mar 28 Python
python PIL模块的基本使用
Sep 29 Python
Python生成随机MAC地址
Mar 10 #Python
Python中实现结构相似的函数调用方法
Mar 10 #Python
Python实现CET查分的方法
Mar 10 #Python
Python实现的批量下载RFC文档
Mar 10 #Python
Python制作CSDN免积分下载器
Mar 10 #Python
Python Tkinter GUI编程入门介绍
Mar 10 #Python
Python格式化css文件的方法
Mar 10 #Python
You might like
浅谈PHP 闭包特性在实际应用中的问题
2009/10/30 PHP
PHP获取php,mysql,apche的版本信息示例代码
2014/01/16 PHP
PHP实现将视频转成MP4并获取视频预览图的方法
2015/03/12 PHP
PHP多态代码实例
2015/06/26 PHP
巧用局部变量提升javascript性能
2014/02/24 Javascript
javascript表单验证和Window详解
2014/12/11 Javascript
JavaScript html5 canvas绘制时钟效果
2016/03/01 Javascript
jQuery树形控件zTree使用小结
2016/08/02 Javascript
BootStrap使用file-input插件上传图片的方法
2016/09/05 Javascript
JS实现的走迷宫小游戏完整实例
2017/07/19 Javascript
返回上一个url并刷新界面的js代码
2020/09/12 Javascript
在Vue中使用Echarts实例图的方法实例
2020/10/10 Javascript
JS实现手风琴特效
2020/11/08 Javascript
python将unicode转为str的方法
2017/06/21 Python
基于Python os模块常用命令介绍
2017/11/03 Python
理解python中生成器用法
2017/12/20 Python
Python使用pandas和xlsxwriter读写xlsx文件的方法示例
2019/04/09 Python
Django model update的多种用法介绍
2020/03/28 Python
Python3 使用map()批量的转换数据类型,如str转float的实现
2019/11/29 Python
Django 如何使用日期时间选择器规范用户的时间输入示例代码详解
2020/05/22 Python
详解Selenium-webdriver绕开反爬虫机制的4种方法
2020/10/28 Python
基于python实现百度语音识别和图灵对话
2020/11/02 Python
Python绘制词云图之可视化神器pyecharts的方法
2021/02/23 Python
Java 中访问数据库的步骤?Statement 和PreparedStatement 之间的区别?
2012/06/05 面试题
软件测试工程师面试问题精选
2016/10/28 面试题
建筑施工员岗位职责
2013/11/26 职场文书
茶叶生产计划书
2014/01/10 职场文书
大学学习生活感言
2014/01/18 职场文书
城管综合整治方案
2014/05/01 职场文书
中秋晚会策划方案
2014/06/12 职场文书
商务英语专业毕业生求职信
2014/07/06 职场文书
中学生逃课检讨书
2015/02/17 职场文书
搞笑婚前保证书
2015/02/28 职场文书
考研英语辞职信
2015/05/13 职场文书
新郎新娘致辞
2015/07/31 职场文书
python 如何做一个识别率百分百的OCR
2021/05/29 Python