亲宝软件园·资讯

展开

python爬取今日说法

Aaron_Yang. 人气:0

实验目的

主要是获取2021年今日说法每期节目主要内容及时间
今日说法的网址为:http://tv.cctv.com/lm/jrsf/index.shtml
当时怎么写的思路有点不太记得了,先把代码贴上,后续有时间再补上。

代码

import xlwt
import re

import requests


# url = "https://tv.cctv.com/lm/jrsf/index.shtml"

def get_data(page):
    url = 'https://api.cntv.cn/NewVideo/getVideoListByColumn?id=TOPC145146466500891' \
          '4&n=1000&sort=desc&p={pageNo}&mode=0&serviceId=tvcctv&cb=Callback'.format(pageNo=page)
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    return response.text
    # print(response.text)


if __name__ == "__main__":

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
    }

    book = xlwt.Workbook(encoding='utf-8', style_compression=0)
    sheet = book.add_sheet('今日说法', cell_overwrite_ok=True)

    count = 0
    for page in range(1,5):
        page_content = get_data(page)
        obj = re.compile(r'url":"(.*?.shtml)"', re.S)
        imgUrl = re.findall(obj, page_content.replace('\\', ''))
        for i in range(len(imgUrl)):
            resp = requests.get(url=imgUrl[i], headers=headers)
            resp.encoding = 'utf-8'

            obj2 = re.compile(r'更新时间:</em>(.*?)</p>', re.S)
            time = re.findall(obj2, resp.text)
            obj3 = re.compile(r'视频简介:</em>(.*?)</p>', re.S)
            jianjie = re.findall(obj3, resp.text)
            content = []
            content.append(time)
            content.append(jianjie)
            for j in range(2):
                sheet.write(count, j, content[j])
                count+=1

    book.save("./data_5.xls")

实验结果

在这里插入图片描述

总结

加载全部内容

相关教程
猜你喜欢
用户评论