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实现的多线程端口扫描工具分享
Jan 21 Python
PyQt5利用QPainter绘制各种图形的实例
Oct 19 Python
分数霸榜! python助你微信跳一跳拿高分
Jan 08 Python
python通过百度地图API获取某地址的经纬度详解
Jan 28 Python
python读取Excel实例详解
Aug 17 Python
python实现自动登录后台管理系统
Oct 18 Python
Python爬虫爬取煎蛋网图片代码实例
Dec 16 Python
django列表筛选功能的实现代码
Mar 27 Python
python如何保存文本文件
Jun 07 Python
python读取excel进行遍历/xlrd模块操作
Jul 12 Python
Python3利用scapy局域网实现自动多线程arp扫描功能
Jan 21 Python
Python pandas求方差和标准差的方法实例
Aug 04 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截取utf-8中文字符串乱码的解决方法
2010/03/29 PHP
php生成数组的使用示例 php全组合算法
2014/01/16 PHP
PHP预定义变量9大超全局数组用法详解
2016/04/23 PHP
记录一次排查PHP脚本执行卡住的问题
2016/12/27 PHP
thinkPHP5框架设置404、403等http状态页面的方法
2018/06/05 PHP
Jquery中Ajax 缓存带来的影响的解决方法
2011/05/19 Javascript
详解基于Bootstrap扁平化的后台框架Ace
2015/11/27 Javascript
BootStrap学习系列之Bootstrap Typeahead 组件实现百度下拉效果(续)
2016/07/07 Javascript
深入理解(function(){... })();
2016/08/16 Javascript
Javascript动画效果(1)
2016/10/11 Javascript
js 中文汉字转Unicode、Unicode转中文汉字、ASCII转换Unicode、Unicode转换ASCII、中文转换
2016/12/06 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
discuz表情的JS提取方法分析
2017/03/22 Javascript
js实现canvas保存图片为png格式并下载到本地的方法
2017/08/31 Javascript
Vue.js组件通信的几种姿势
2017/10/23 Javascript
webpack vue 项目打包生成的文件,资源文件报404问题的修复方法(总结篇)
2018/01/09 Javascript
vue3.0 CLI - 3.2 路由的初级使用教程
2018/09/20 Javascript
详解小程序之简单登录注册表单验证
2019/05/13 Javascript
Nodejs监控事件循环异常示例详解
2019/09/22 NodeJs
修改Python的pyxmpp2中的主循环使其提高性能
2015/04/24 Python
python模块之time模块(实例讲解)
2017/09/13 Python
Python实现将照片变成卡通图片的方法【基于opencv】
2018/01/17 Python
django初始化数据库的实例
2018/05/27 Python
python实现寻找最长回文子序列的方法
2018/06/02 Python
python实现控制台打印的方法
2019/01/12 Python
Python实现Event回调机制的方法
2019/02/13 Python
python中Django文件上传方法详解
2020/08/05 Python
Python获取android设备cpu和内存占用情况
2020/11/15 Python
自1926年以来就为冰岛保持温暖:66°North
2020/11/27 全球购物
将一个文本文件的内容按倒序打印出来
2015/01/05 面试题
.net笔试题
2014/03/03 面试题
linux面试题参考答案(7)
2014/07/24 面试题
2015年政务公开工作总结
2015/05/19 职场文书
学校财务管理制度
2015/08/04 职场文书
《勇者辞职不干了》ED主题曲无字幕动画MV公开
2022/04/13 日漫
Python中的matplotlib绘制百分比堆叠柱状图,并为每一个类别设置不同的填充图案
2022/04/20 Python