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中使用成员运算符的示例
May 13 Python
在Django的视图中使用form对象的方法
Jul 18 Python
Python如何获取系统iops示例代码
Sep 06 Python
python实现按任意键继续执行程序
Dec 30 Python
Python中偏函数用法示例
Jun 07 Python
Python IDLE清空窗口的实例
Jun 25 Python
一篇文章弄懂Python中所有数组数据类型
Jun 23 Python
python在新的图片窗口显示图片(图像)的方法
Jul 11 Python
在Django model中设置多个字段联合唯一约束的实例
Jul 17 Python
给 TensorFlow 变量进行赋值的方式
Feb 10 Python
Pycharm 安装 idea VIM插件的图文教程详解
Feb 21 Python
Python使用itcaht库实现微信自动收发消息功能
Jul 13 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使用ffmpeg给视频增加字幕显示的方法
2015/03/12 PHP
PHP的运行机制与原理(底层)
2015/11/16 PHP
Yii2实现UploadedFile上传文件示例
2017/02/15 PHP
Yii1.1中通过Sql查询进行的分页操作方法
2017/03/16 PHP
A标签中通过href和onclick传递的this对象实现思路
2013/04/19 Javascript
JSON传递bool类型数据的处理方式介绍
2013/09/18 Javascript
浅析Js中的单引号与双引号问题
2013/11/06 Javascript
javascript实现的一个随机点名功能
2014/08/26 Javascript
javascript实现回车键提交表单方法总结
2015/01/10 Javascript
javascript判断移动端访问设备并解析对应CSS的方法
2015/02/05 Javascript
深入解析JavaScript中函数的Currying柯里化
2016/03/19 Javascript
JS获取元素多层嵌套思路详解
2016/05/16 Javascript
使用JS location实现搜索框历史记录功能
2019/12/23 Javascript
Vue路由守卫及页面登录权限控制的设置方法(两种)
2020/03/31 Javascript
分享Python开发中要注意的十个小贴士
2016/08/30 Python
Python温度转换实例分析
2018/01/17 Python
python使用mysql的两种使用方式
2018/03/07 Python
Python终端输出彩色字符方法详解
2020/02/11 Python
探秘TensorFlow 和 NumPy 的 Broadcasting 机制
2020/03/13 Python
基于python SMTP实现自动发送邮件教程解析
2020/06/02 Python
Python虚拟环境的创建和包下载过程分析
2020/06/19 Python
基于HTML5的WebSocket的实例代码
2018/08/15 HTML / CSS
Etam艾格英国官网:法国著名女装品牌
2019/04/15 全球购物
俄罗斯小米家用电器、电子产品和智能家居商店:Poood.ru
2020/04/03 全球购物
德国W家官网,可直邮中国的母婴商城:Windeln.de
2021/03/03 全球购物
python+selenium小米商城红米K40手机自动抢购的示例代码
2021/03/24 Python
函授毕业生的自我鉴定
2013/11/26 职场文书
技校个人求职信范文
2014/01/25 职场文书
党的群众路线对照检查材料
2014/08/27 职场文书
2014年国庆节演讲稿精选范文1500字
2014/09/25 职场文书
2015年元旦晚会活动总结(学生会)
2014/11/28 职场文书
刑事附带民事诉讼答辩状
2015/05/22 职场文书
亮剑观后感600字
2015/06/05 职场文书
长辈生日祝福语大全(72句)
2019/08/09 职场文书
Python还能这么玩之只用30行代码从excel提取个人值班表
2021/06/05 Python
PostgreSQL数据库去除重复数据和运算符的基本查询操作
2022/04/12 PostgreSQL