Python教程网
--左手Python,右手AI!

如何用 Python 每天给你爱的读者发早报?

早报

最近和一个朋友唠嗑,听她吐槽了好久……

她是一个社群运营,每天早上收集信息、整理、排版、到推送社群,大概要花费30分钟,需要花费大量的时间和精力,苦不堪言。

那么有没有办法将这个流程自动化呢?于是乎,我们想到了 「 除了生孩子无所不能的 Python 」,请接着看!


⬆️早报图片

思路很简单,分为3步:
1.从目标网站采集信息;
2.将采集到的信息生成早报图片
3.将生成的图片发送到微信群或好友


⬆️实现流程

一、早报数据收集

网络上有很多提供早报的网站,这里为了避免做广告,但是为了演示方便,只提供地址,不说明名字,下文将我采集的网站称为A网站,A网站有专门的早报模块


⬆️A网站

1.获取最新日报的url

首先获取A网站最新早报页面的链接,通过查看网页源代码发现,所有的展示信息在页面 li 中,我们要获取的链接的地址正好在h2中,所以分析完毕开始提取链接

⬆️image.png
首先引入相关的网络请求库u,如下

import requests
from bs4 import BeautifulSoup

点击第一个早报信息进入后链接为https://www.pmtown.com/archives/197318.html,而我们使用find方式找到最新日报页面的链接为相对路径/archives/197318.html,所以需要我们手动组装完整的URL,具体见下方。

#获取第一个早报的url
obj1 = requests.get('http://www.pmtown.com/archives/category/早报')
url_obj = BeautifulSoup(obj1.text, 'lxml')
url = url_obj.find('h2').find('a').get('href')
first_url = 'http://www.pmtown.com' + url

2.获取日报页面的日报内容


⬆️页面1
制作早报时,我们只需要新闻的标题即可,通过分析发现页面比较简单,所有的标题都在p下面,所以我们直接提取内容

# 获取当前页
obj = requests.get(first_url)
obj_1 = BeautifulSoup(obj.text, 'lxml')
titles = obj_1.findAll('p')

# 获得新闻标题
a = []
for title in titles:
    a.append(title.get_text())

获取的内容部分截图如下


⬆️内容截图

3.文本处理

A网站日报的内容有科技头条,国内动态,海外动态和投资收购四个模块,实质得到的文本除了“科技头条”得到的日报标题是列表,而其他3个模块的日报标题各自在一整段字符串中,所以就要对字符串进行处理,使其成为列表


⬆️文本处理

定义函数,将国内动态,海外动态和投资收购的日报标题分割开来,组成新的列表,这样日报的4类内容的格式就统一了

# 将新闻文本格式统一,生成新的列表
def get_text(text_orgin):
    #将标题的序号统一替换为‘sp’,然后将整段文本分割组成新的日报标题列表
    first_list = re.sub(r'\d{1,2}、', 'SP', text_orgin)
    mid_list = first_list.split('SP')
    finnal_list = mid_list[1:len(mid_list)]
    return finnal_list

上述步骤中,我们把标题的序号替换了,所以需要需要加上新的序号,具体操作

# 定义函数,给信息加上编号,输出列表
def inf_list(inf_orgin):
    inf_after = []
    for num, single_info in enumerate(inf_orgin):
        inf_after.append(u'%s、%s' % ((num + 1), single_info))
    return inf_after

二、生成早报图片

首先导入画图的库,这里使用PIL库

from PIL import Image, ImageDraw, ImageFont

1.画日报报头

设置字体类型和颜色,字体类型后续会用到,字体需要填写自己电脑上有的字体,window一般在C:/Windows/Fonts文件夹下,如果字体设置错误,程序会报错。

# 设置字体样式
font_type = 'C:/Windows/Fonts/simkai.ttf'
font_medium_type = 'C:/Windows/Fonts/simkai.ttf'
header_font = ImageFont.truetype(font_medium_type, 55)
title_font = ImageFont.truetype(font_medium_type, 20)
font = ImageFont.truetype(font_type, 38)
color = "#726053"
color1 = "#294E76"

(1)画题目

header_x 和header_y是要画图的坐标,color是题目的颜色,header_font是题目的字体类型

# 开始画图
header = '互联网日报'
header_x = 130
header_y = 200
draw.text((header_x, header_y), u'%s' % header, color, header_font)

(2)画副标题

title = '由python脚本自动生成'
title_x = header_x
title_y = header_y + 80
draw.text((title_x, title_y), u'%s' % title, color1, title_font)

(3)添加当前时间

在图片上添加生成图片的时间,单纯是为了显得高大上
首先引入import time模块,然后开始画图

cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
cur_time_x = 666
cur_time_y = title_y
cur_time_font = ImageFont.truetype(font_type, 20)
draw.text((cur_time_x, cur_time_y), u'%s' %cur_time, color, cur_time_font)


⬆️报头效果预览

2.画日报内容

因为新闻标题很长(最多2行),而图片是有宽度上限的,所以必须考虑换行的问题,我的处理方式是将原列表直接按照设定的宽度(我设定为750px)处理成为新列表,具体操作见下

def old_to_new_list(oldlist):
    newlist = []
    for single_text in oldlist:
        if font.getsize(single_text.strip())[0] < 750 or font.getsi(single_text.strip()) == 750:
            newlist.append(single_text)
        else:
            strList = []
            newStr = ''
            index = 0
            # 从字符串single_text逐个取字,直到总长度大于750px
            for item in single_text:
                newStr += item
            #gitsize可以同时输出字符串的宽和高
                if font.getsize(newStr.strip())[0] > 750:
                    newlist.append(newStr[:-1])
                    newStr = ''
                    # 如果后面长度没有750px长就返回这部分字符串
                    if font.getsize(single_text[index:])[0] < 750:
                        newlist.append(single_text[index:])
                    else:
                        break

                index += 1
    print(newlist)
    return newlist

接下来定义函数来画图,传入画图开始的的坐标:x,y值,要画的列表list,以及字体高度和标题文字;做函数的优点就在于不用重复写代码

def draw_info(x, y, the_list, linehigh, title_text):
    draw.text((x, y), u'%s' % (title_text), color, font)
    for num, info in enumerate(the_list):
        height = num * linehigh
        draw.text((x, y + height + 80), u'%s' % (info), color, font)

比如绘制“科技新闻”,我们设定好绘画坐标,标题,内容列表等,调用上面的函数即可,其他“科技新闻”,“海外新闻”和“融资收购”类似不做演示,原理相同

# 绘制科技
keji_x = title_x - 30
keji_y = title_y + 88
title_text = '【科技新闻】'
keji_text = a[1:gn:2]
keji_newlist = old_to_new_list(keji_text)
draw_info(keji_x, keji_y, keji_newlist, linehigh, title_text)

来看成品


⬆️日报成品

3.将日报发送给好友或微信群

首先引入wxpy库,wxpy是python专门用于调取微信功能的库

from wxpy import *
import time
#获取系统时间
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
#初始化
bot = Bot()

你可以把日报发送给好友,只需要填写好友的昵称,如果要发给多个好友,加入循环结构即可

myfriends = bot.friends().search('好友昵称')[0]
myfriends.send('python自动早报到了 ' + cur_time)
myfriends.send_image('日报.jpeg')


⬆️早报
你也可以选择把日报发送给微信群,操作类似

groups = ['微信群的名字']
for send_OBJ in groups:
    my_groups = bot.groups().search(groups)[0]
    my_groups.send('python自动早报到了 ' + cur_time)
    my_groups.send_image('日报.jpeg')

如果有自己的微信群,需要每天做早报;或者你本身就是互联网运营等职业,相信能给你节约大量的时间!

做一次的事寻找可行解,重复做的事寻找最优解。如果需要完整代码,可以扫下方二维码回复「日报」即可获取哦。

赞(29)
未经允许不得转载:Python教程网 » 如何用 Python 每天给你爱的读者发早报?
分享到: 更多 (0)

评论 71

  1. #1

    Men who take nitrate medications should not take Stendra because the combination of these two
    medications can lead to a sudden drop in blood pressure.
    will 10 year old viagra work buy generic 100mg viagra online

    匿名3个月前 (10-30)回复
  2. #2

    Reply tara says: February 6, 2015 at 11:46 am Thank you so much for this informative website.
    https://llviabest.com buying viagra online
    forum

    匿名3个月前 (11-05)回复
  3. #3

    Sterile cystitis is a disease that is not completely understood, and
    often stress may be a strong trigger for this problem.
    http://siviagmen.com viagra online
    canada

    匿名3个月前 (11-05)回复
  4. #4

    which is the best viagra cialis or levitra purevigra.com dominican republic viagra drink

    匿名2个月前 (11-16)回复
  5. #5

    viagra fГјr junge menschen come usare viagra hur lГҐngt innan ska man ta viagra

    匿名2个月前 (11-17)回复
  6. #6

    blogs for reliable genric viagra https://paradiseviagira.com buy oral viagra online

    匿名2个月前 (11-17)回复
  7. #7

    how to buy viagra forum pilule viagra pas cher average age men need viagra

    匿名2个月前 (11-17)回复
  8. #8

    is viagra available in indian medical shops jeftina viagra viagra fГјr die frau flГјssig

    匿名2个月前 (11-17)回复
  9. #9

    viagra 100 mg best price https://paradiseviagira.com get perscription for viagra scottsdale az

    匿名2个月前 (11-18)回复
  10. #10

    rappers and viagra https://purevigra.com/ viagra how long does it last

    匿名2个月前 (11-18)回复
  11. #11

    discount viagra online generic viagra and dapoxetine viagra sub

    匿名2个月前 (11-18)回复
  12. #12

    viagra vs. cialis vs. levitra which is best viagra en droguerias can viagra be taken long term

    匿名2个月前 (11-19)回复
  13. #13

    discreet viagra viagra generic cheap viagra without prescription in australia

    匿名2个月前 (11-19)回复
  14. #14

    Where can you buy viagra in south africa https://miraclevigra.com/ where
    can buy viagra

    匿名2个月前 (11-21)回复
  15. #15

    Viagra over the counter united states https://lightvigra.com buy viagra online
    australia

    匿名2个月前 (11-21)回复
  16. #16

    viagra prescription cost australia https://buybuyviamen.com/ which viagra is good

    匿名2个月前 (11-21)回复
  17. #17

    Order sildenafil citrate https://mygoviagar.com/ generic viagra
    100mg pills

    匿名2个月前 (11-21)回复
  18. #18

    Sildenafil price https://hopeviagrin.com/ where can i buy sildenafil over the
    counter

    匿名2个月前 (11-21)回复
  19. #19

    medicine viagra india tadalafil for women compare prices viagra

    匿名2个月前 (11-21)回复
  20. #20

    viagra medicare australia viagra levitra cialis cost comprar viagra sin tarjeta de credito

    匿名2个月前 (11-24)回复
  21. #21

    buy viagra online legally how much is sildenafil order generic viagra from india

    匿名2个月前 (11-24)回复
  22. #22

    viagra best buy coupon viagra 25mg price how to purchase viagra pills

    匿名2个月前 (11-24)回复
  23. #23

    viagra for cheap canada viagra buy over the counter generic sildenafil

    匿名2个月前 (11-25)回复
  24. #24

    movie on viagra find viagra in melbourne pastillas de viagra natural

    匿名2个月前 (11-25)回复
  25. #25

    female viagra tablets sildenafil 100mg price in india online viagra safe

    匿名2个月前 (11-25)回复
  26. #26

    where to buy sildenafil without prescription buying viagra nz how to buy viagra pills

    匿名2个月前 (11-26)回复
  27. #27

    online viagra coupon where can you buy over the counter viagra generic viagra 100mg price in india

    匿名2个月前 (11-26)回复
  28. #28

    viagra in england how to buy viagra price in india 2010 viagra horse commercial

    匿名2个月前 (11-27)回复
  29. #29

    how much is over the counter viagra can you buy viagra over the counter nz generic sildenafil 20 mg cost

    匿名2个月前 (11-27)回复
  30. #30

    narrative essay writing research paper video writing about a book in an essay

    匿名2个月前 (11-28)回复
  31. #31

    qualitative dissertation writing a proper essay writing an essay in first person

    匿名2个月前 (11-29)回复
  32. #32

    guidelines in making a research paper the persuasive essay things to write a descriptive essay about

    匿名2个月前 (11-29)回复
  33. #33

    college essays music essay jamestown dissertation writing experts

    匿名2个月前 (11-30)回复
  34. #34

    write my paper who can do my accounting homework write essays for cash

    匿名2个月前 (11-30)回复
  35. #35

    thesis for an essay homework help.com math homework

    匿名2个月前 (12-01)回复
  36. #36

    thesis statement for argumentative essay on abortion best dissertation help high school essay help

    匿名2个月前 (12-01)回复
  37. #37

    algebra help online australian assignment help paper help

    匿名2个月前 (12-01)回复
  38. #38

    Buy essay papers buyessayhelpbtg.com buy essay paper

    匿名2个月前 (12-01)回复
  39. #39

    writing argumentative essay conclusion and recommendation research paper writing a college level essay

    匿名2个月前 (12-01)回复
  40. #40

    Dissertation proposal example https://dissertationhelpvfh.com
    dissertation statistics help

    匿名2个月前 (12-01)回复
  41. #41

    research paper essays trig homework assignment college essay expert

    匿名2个月前 (12-02)回复
  42. #42

    purpose of essay writing essay writing handbook essay 5th grade

    匿名2个月前 (12-02)回复
  43. #43

    science homework help dissertation editing services college essays harvard

    匿名2个月前 (12-03)回复
  44. #44

    viagra in uae viagra melbourne viagra for sale no prescription

    匿名2个月前 (12-03)回复
  45. #45

    viagra cialis levitra sample pack use paypal to buy viagra viagra syd

    匿名2个月前 (12-03)回复
  46. #46

    boots viagra online viagra en uk viagra online

    匿名2个月前 (12-04)回复
  47. #47

    cialis 20mg no prescription buy viagra cialis mix online chewable cialis

    匿名2个月前 (12-08)回复
  48. #48

    generic cialis reviews buy brand cialis overnight cialis doesn\’t work?

    匿名2个月前 (12-10)回复
  49. #49

    generic cialis 10mg cialis buy cialis paypal

    匿名2个月前 (12-10)回复
  50. #50

    brand cialis in canada buy 36 hour cialis no rx cialis

    匿名2个月前 (12-10)回复
  51. #51

    viagra hong kong viagra using paypal buy viagra

    匿名2个月前 (12-11)回复
  52. #52

    germany cialis professional cialis on line cialis without a script

    匿名2个月前 (12-11)回复
  53. #53

    the effects that viagra and cialis have on women buy viagra in melb viagra 50mg pills

    匿名2个月前 (12-11)回复
  54. #54

    generic viagra cialis paypal free cialis sample canada cialis pill canada

    匿名2个月前 (12-11)回复
  55. #55

    pay pal for cialis cheap cialis online generic cialis daily online

    匿名1个月前 (12-12)回复
  56. #56

    womens viagra can you buy viagra over the counter in the uk viagra vs cialis vs levitra reviews

    匿名1个月前 (12-12)回复
  57. #57

    red viagra buying viagra online in netherland,paypal where can i buy viagra in exeter

    匿名1个月前 (12-12)回复
  58. #58

    cialis generic shopping cialis soft tabs generic cialis sale

    匿名1个月前 (12-12)回复
  59. #59

    viagra paypal australia soft viagra viagra and things like it

    匿名1个月前 (12-12)回复
  60. #60

    viagra alternatives healthstore viagra online stores is viagra prescription only

    匿名1个月前 (12-12)回复
  61. #61

    generic viagra 100mg sildenafil viagra online by paypal where to get viagra in bangalore

    匿名1个月前 (12-13)回复
  62. #62

    viagra/cialis bay viagra on line celiac. viagra

    匿名1个月前 (12-13)回复
  63. #63

    farmacias viagra espana LiseMirl buy cialis professional cackVial levitra bayer 20mg

    匿名1个月前 (12-13)回复
  64. #64

    viagra/overnight shipping can i buy viagra over the counter in canada before and after viagra

    匿名1个月前 (12-14)回复
  65. #65

    sams viagra most reliable viagra shelf life of viagra

    匿名1个月前 (12-15)回复
  66. #66

    viagra pills 90 viagra dapoxetine next day shipping buy viagra cheap usa

    匿名1个月前 (12-16)回复
  67. #67

    buy viagra online super viagra plus free samples viagra cialis

    匿名1个月前 (12-17)回复
  68. #68

    Do you have a spam issue on this site; I also am a blogger, and I was wanting to
    know your situation; many of us have created some nice practices and we
    are looking to exchange techniques with others, be sure to shoot me an e-mail if interested.

    my webpage – porn videos (http://toons-fear.net/cgi-bin/atx/out.cgi?id=13&tag=top&trade=https://anyxxx.com/search/kiss-japanese-lesbian/)

    匿名1个月前 (12-22)回复
  69. #69

    canadian online pharmacy rx pharmacy best drugstore setting powder

    匿名2周前 (01-09)回复
  70. #70

    pharmacy rx world http://pharmacy-onlineasxs.com/ discount pharmacy

    匿名2周前 (01-10)回复
  71. #71

    24 hour pharmacy near me rx online pharmacy no prescription

    匿名2周前 (01-11)回复