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远程登录代码
Apr 29 Python
python的Template使用指南
Sep 11 Python
python获取当前时间对应unix时间戳的方法
May 15 Python
使用Python的urllib2模块处理url和图片的技巧两则
Feb 18 Python
Python 获取当前所在目录的方法详解
Aug 02 Python
vue.js实现输入框输入值内容实时响应变化示例
Jul 07 Python
Python get获取页面cookie代码实例
Sep 12 Python
Django中如何使用sass的方法步骤
Jul 09 Python
python实现知乎高颜值图片爬取
Aug 12 Python
pandas 像SQL一样使用WHERE IN查询条件说明
Jun 05 Python
Cpython解释器中的GIL全局解释器锁
Nov 09 Python
python+playwright微软自动化工具的使用
Feb 02 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/11/19 PHP
PHP数组无限分级数据的层级化处理代码
2012/12/29 PHP
php+mysql数据库实现无限分类的方法
2014/12/12 PHP
PHP getDocNamespaces()函数讲解
2019/02/03 PHP
PHP7 其他语言层面的修改
2021/03/09 PHP
javascript如何动态加载表格与动态添加表格行
2013/11/27 Javascript
jquery禁用右键单击功能屏蔽F5刷新
2014/03/17 Javascript
Jquery日历插件制作简单日历
2015/10/28 Javascript
深入理解jquery跨域请求方法
2016/05/18 Javascript
为Jquery EasyUI 组件加上清除功能的方法(详解)
2017/04/13 jQuery
Vue使用json-server进行后端数据模拟功能
2018/04/17 Javascript
NodeJs项目中关闭ESLint的方法
2018/08/09 NodeJs
使用JavaScript破解web
2018/09/28 Javascript
JavaScript Image对象实现原理实例解析
2020/08/26 Javascript
[00:35]DOTA2上海特级锦标赛 MVP.Phx战队宣传片
2016/03/04 DOTA
python命令行参数解析OptionParser类用法实例
2014/10/09 Python
Python中函数参数设置及使用的学习笔记
2016/05/03 Python
浅谈python为什么不需要三目运算符和switch
2016/06/17 Python
Django数据库表反向生成实例解析
2018/02/06 Python
Python SMTP发送邮件遇到的一些问题及解决办法
2018/10/24 Python
对python内置map和six.moves.map的区别详解
2018/12/19 Python
Django实现跨域的2种方法
2019/07/31 Python
python 叠加等边三角形的绘制的实现
2019/08/14 Python
Python爬虫:url中带字典列表参数的编码转换方法
2019/08/21 Python
利用python3筛选excel中特定的行(行值满足某个条件/行值属于某个集合)
2020/09/04 Python
基于Python实现体育彩票选号器功能代码实例
2020/09/16 Python
Html5+JS实现手机摇一摇功能
2015/04/24 HTML / CSS
List, Set, Map是否继承自Collection接口?
2016/05/16 面试题
消防安全汇报材料
2014/02/08 职场文书
学院党的群众路线教育实践活动整改方案
2014/10/04 职场文书
幼儿园见习报告
2014/10/30 职场文书
文明单位申报材料
2014/12/23 职场文书
团组织推优材料
2014/12/29 职场文书
感谢信格式范文
2015/01/22 职场文书
公务员年度个人总结
2015/02/12 职场文书
Pytorch 统计模型参数量的操作 param.numel()
2021/05/13 Python