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过滤函数filter()使用自定义函数过滤序列实例
Aug 26 Python
Python解决鸡兔同笼问题的方法
Dec 20 Python
Python读取sqlite数据库文件的方法分析
Aug 07 Python
Python的地形三维可视化Matplotlib和gdal使用实例
Dec 09 Python
python数据封装json格式数据
Mar 04 Python
python实现随机梯度下降法
Mar 24 Python
Pandas GroupBy对象 索引与迭代方法
Nov 16 Python
对python修改xml文件的节点值方法详解
Dec 24 Python
对Python 获取类的成员变量及临时变量的方法详解
Jan 22 Python
Python实现的企业粉丝抽奖功能示例
Jul 26 Python
使用Python发现隐藏的wifi
Mar 04 Python
python统计mysql数据量变化并调用接口告警的示例代码
Sep 21 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
文件系统基本操作类
2006/11/23 PHP
用JavaScrpt实现文件夹简单轻松加密的实现方法图文
2008/09/08 Javascript
javascript 短路法代码精简
2009/08/20 Javascript
js jquery ajax的几种用法总结(及优缺点介绍)
2014/01/28 Javascript
深入分析原生JavaScript事件
2014/12/29 Javascript
jQuery知识点整理
2015/01/30 Javascript
jquery中EasyUI使用技巧小结
2015/02/10 Javascript
js使用onmousemove和onmouseout获取鼠标坐标的方法
2015/03/31 Javascript
JavaScript生成福利彩票双色球号码
2015/05/15 Javascript
JavaScript中使用concat()方法拼接字符串的教程
2015/06/06 Javascript
详解JavaScript ES6中的模板字符串
2015/07/28 Javascript
iframe跨域通信封装详解
2015/08/11 Javascript
JS控制页面跳转时未请求要跳转的地址怎么回事
2016/10/14 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
JavaScript中localStorage对象存储方式实例分析
2017/01/12 Javascript
使用Vue开发动态刷新Echarts组件的教程详解
2018/03/22 Javascript
Vue条件循环判断+计算属性+绑定样式v-bind的实例
2018/09/18 Javascript
Vue组件通信入门之Provide和Inject机制
2019/12/29 Javascript
浅谈vue的第一个commit分析
2020/06/08 Javascript
python以环状形式组合排列图片并输出的方法
2015/03/17 Python
50行Python代码实现人脸检测功能
2018/01/23 Python
pandas的object对象转时间对象的方法
2018/04/11 Python
解决sublime+python3无法输出中文的问题
2018/12/12 Python
python实现画循环圆
2019/11/23 Python
python Matplotlib数据可视化(2):详解三大容器对象与常用设置
2020/09/30 Python
HTML+CSS3 模仿Windows7 桌面效果
2010/06/17 HTML / CSS
Aveda美国官网:天然护发产品、洗发水、护发素和沙龙
2016/12/09 全球购物
日本民宿预约平台:STAY JAPAN
2017/07/01 全球购物
思想政治自我鉴定
2013/10/06 职场文书
职业教育毕业生求职信
2013/11/09 职场文书
工作失职检讨书范文
2014/01/16 职场文书
红旗团支部事迹材料
2014/01/27 职场文书
降消项目实施方案
2014/03/30 职场文书
小学班干部竞选演讲稿
2014/04/24 职场文书
2019最新劳动仲裁申请书!
2019/07/08 职场文书
社交电商模式的兴起:这些新的商机千万别错过
2019/07/26 职场文书