Python简单爬取“中国日报”新浪微博的早晚安鼓励话语

有时睡醒睡前会去看中国日报的早晚安,挺有意思的。考虑到以后可能会用到这方面内容的爬取,就试着先把功能代码写了。写的比较简单,仅供参考。

具体实现可以写个定时脚本早上和晚上爬取内容和图片推送到服务器即可。

在这里插入图片描述
在这里插入图片描述

# -*- coding  = utf-8 -*-
# @Time : 2021/7/23 20:52
# @Author : fangfang
# @File : requestTest.py
# @Software : PyCharm
import json
import requests
import re
from bs4 import BeautifulSoup

url = "https://weibo.com/chinadailywebsite"
headers = {
    "User-Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/91.0.4472.124 Safari/537.36",
    "Cookie": "" #补充自己的cookie~
}

imgRe = re.compile(r'<img src="(.*?)"/>', re.S)
timeRe = re.compile(r'\d\d\d\d-\d\d-\d\d 0[07]:0[0-1]', re.S)  # 00:00和07:00两个时间点,考虑1分钟误差 --但实际可能对方不是人工发的,是机器定时发的。。


def main():
    r = requests.get(url, headers=headers)
    if r.status_code == 200:
        html = re.findall(r'<script>FM.view(.*)</script>', r.text)  # 将script标签内容提取出
        for i in html:
            if re.search(r'WB_text', i) != None:  # 取出特定script段 其实就是html的最后一个
                i = i.strip('(').strip(')')  # 字串去掉括号
                data_jason = json.loads(i)  # 将字串载入成字典档
                soup = BeautifulSoup(data_jason['html'], 'lxml')  # 字典档当中只提取html对应的代码
                # print(soup)
                tags = soup.find_all('div', attrs={"class": "WB_feed_detail clearfix"})  # 提取文字的标签
                for tag in tags:
                    tag_str = str(tag)
                    if (re.search(timeRe, tag_str)) != None:
                        # print(tag)
                        content = tag.find_all('div', attrs={"class": "WB_text W_f14"})[0].text.replace('  ','')  # 去掉开头的空格
                        print(content)
                        img_src = re.findall(imgRe, tag_str)
                        if len(img_src) != 0:
                            img_src = "https:" + img_src[0]
                        else:
                            print("无图片", end="")

                        print(img_src)
    else:
        print("获取失败")


if __name__ == "__main__":  # 当程序执行时
    main()

好吧,刚发现中国日报好像还真是人工发的,而且代码和方法还存在挺多问题的,有时间再优化更新,后续会补充定时脚本和服务器的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值