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发送邮件的实例代码(支持html、图片、附件)
Mar 04 Python
在Python中使用matplotlib模块绘制数据图的示例
May 04 Python
在Python中操作列表之List.append()方法的使用
May 20 Python
Python实现读取机器硬件信息的方法示例
Jun 09 Python
python顺序的读取文件夹下名称有序的文件方法
Jul 11 Python
python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】
Jun 17 Python
通过PHP与Python代码对比的语法差异详解
Jul 10 Python
django将数组传递给前台模板的方法
Aug 06 Python
python爬虫 2019中国好声音评论爬取过程解析
Aug 26 Python
python实现按首字母分类查找功能
Oct 31 Python
使用python的turtle绘画滑稽脸实例
Nov 21 Python
Python 如何展开嵌套的序列
Aug 01 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之第六天
2006/10/09 PHP
php 文件上传实例代码
2012/04/19 PHP
推荐一款MAC OS X 下php集成开发环境mamp
2014/11/08 PHP
php二维数组合并及去重复的方法
2015/03/04 PHP
PHP中使用BigMap实例
2015/03/30 PHP
php+redis实现注册、删除、编辑、分页、登录、关注等功能示例
2017/02/15 PHP
JS中==与===操作符的比较
2009/03/21 Javascript
firefox下input type=&quot;file&quot;的size是多大
2011/10/24 Javascript
javascript 日期时间 转换的方法
2013/02/21 Javascript
jquery ztree实现下拉树形框使用到了json数据
2014/05/14 Javascript
jquery仿搜索自动联想功能代码
2014/05/23 Javascript
js实现字符串转日期格式的方法
2015/05/20 Javascript
深入浅析JavaScript中with语句的理解
2016/05/12 Javascript
Bootstrap基本插件学习笔记之Popover提示框(19)
2016/12/08 Javascript
bootstrap的常用组件和栅格式布局详解
2017/05/02 Javascript
jQuery树插件zTree使用方法详解
2017/05/02 jQuery
vue 将页面公用的头部组件化的方法
2017/12/18 Javascript
在 Angular-cli 中使用 simple-mock 实现前端开发 API Mock 接口数据模拟功能的方法
2018/11/28 Javascript
JavaScript时间与时间戳的转换操作实例分析
2018/12/07 Javascript
Vue解决移动端弹窗滚动穿透问题
2020/12/15 Vue.js
python常见数制转换实例分析
2015/05/09 Python
解决Python下imread,imwrite不支持中文的问题
2018/12/05 Python
python使用socket 先读取长度,在读取报文内容示例
2019/09/26 Python
Python绘制三角函数图(sin\cos\tan)并标注特定范围的例子
2019/12/04 Python
python实现按关键字筛选日志文件
2019/12/24 Python
keras读取h5文件load_weights、load代码操作
2020/06/12 Python
阿玛尼意大利官网:Armani意大利
2018/10/30 全球购物
盖尔斯工厂店:GUESS Factory
2020/01/21 全球购物
日本化妆品植村秀俄罗斯官方网站:Shu Uemura俄罗斯
2020/02/01 全球购物
最新自我评价范文
2013/11/16 职场文书
企业管理毕业生求职信
2014/03/11 职场文书
大学毕业生求职自荐书
2014/06/05 职场文书
幼儿园教师师德师风演讲稿:爱我所爱 无悔青春
2014/09/10 职场文书
2014年国庆节演讲稿精选范文1500字
2014/09/25 职场文书
2015年中个人总结范文
2015/03/10 职场文书
2015年工商所工作总结
2015/05/21 职场文书