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 15 Python
Python使用chardet判断字符编码
May 09 Python
详解字典树Trie结构及其Python代码实现
Jun 03 Python
python实现可以断点续传和并发的ftp程序
Sep 13 Python
Python实现的读取/更改/写入xml文件操作示例
Aug 30 Python
PyCharm搭建Spark开发环境实现第一个pyspark程序
Jun 13 Python
在pytorch中为Module和Tensor指定GPU的例子
Aug 19 Python
python3.7调试的实例方法
Jul 21 Python
django和flask哪个值得研究学习
Jul 31 Python
python 实用工具状态机transitions
Nov 21 Python
python区块链持久化和命令行接口实现简版
May 25 Python
python实现学员管理系统(面向对象版)
Jun 05 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通过header发送自定义数据方法
2018/01/18 PHP
为JavaScript添加重载函数的辅助方法
2010/07/04 Javascript
jquery 无限级联菜单案例分享
2013/03/26 Javascript
jQuery 网易相册鼠标移动显示隐藏效果实现代码
2013/03/31 Javascript
javascript正则表达式基础知识入门
2015/04/20 Javascript
javascript实现的图片切割多块效果实例
2015/05/07 Javascript
微信小程序 登录实例详解
2017/01/16 Javascript
HTML5+jQuery实现搜索智能匹配功能
2017/03/24 jQuery
BootStrap自定义popover,点击区域隐藏功能的实现
2018/01/23 Javascript
基于vue.js中事件修饰符.self的用法(详解)
2018/02/23 Javascript
Vue2.0 实现单选互斥的方法
2018/04/13 Javascript
Nuxt配合Node在实际生产中的应用详解
2018/08/07 Javascript
Vue 之孙组件向爷组件通信的实现
2019/04/23 Javascript
详解微信小程序开发用户授权登陆
2019/04/24 Javascript
使用微信SDK自定义分享的方法
2019/07/03 Javascript
将RGB值转换为灰度值的简单算法
2019/10/09 Javascript
Python常用模块用法分析
2014/09/08 Python
Python中input和raw_input的一点区别
2014/10/21 Python
利用Python找出序列中出现最多的元素示例代码
2017/12/08 Python
opencv python统计及绘制直方图的方法
2019/01/21 Python
使用python serial 获取所有的串口名称的实例
2019/07/02 Python
python 利用jinja2模板生成html代码实例
2019/10/10 Python
pycharm 激活码及使用方式的详细教程
2020/05/12 Python
解决Django响应JsonResponse返回json格式数据报错问题
2020/08/09 Python
纯HTML+CSS3制作导航菜单(附源码)
2013/04/24 HTML / CSS
英国领先的葡萄酒专家:Majestic Wine
2017/05/30 全球购物
俄罗斯小米家用电器、电子产品和智能家居商店:Poood.ru
2020/04/03 全球购物
历史学专业大学生找工作的自我评价
2013/10/16 职场文书
《小猫刮胡子》教学反思
2014/02/21 职场文书
药剂专业求职信
2014/06/20 职场文书
房地产端午节活动方案
2014/08/24 职场文书
公安领导班子四风问题个人整改措施思想汇报
2014/10/09 职场文书
2014财务年终工作总结
2014/12/08 职场文书
公司劳动纪律管理制度
2015/08/04 职场文书
2016年优秀共产党员先进事迹材料
2016/02/29 职场文书
springboot + mongodb 通过经纬度坐标匹配平面区域的方法
2021/11/01 MongoDB