【Python爬虫篇】BeautifulSoup之腾讯课堂课程信息并以xls形式保存

博客介绍了使用Python爬取腾讯课堂名称和内容并保存的方法,重点介绍了xlwt库的安装与使用,给出了创建工作簿、工作表及写入数据并保存的示例代码,还提到代码运行后将内容存入指定Excel表中。

Python爬取腾讯课堂名称和内容保存需要用到xlwt库

一、介绍xlwt库

1.1xlwt库安装

pip install xlwt

1.2xlwt使用介绍

work= xlwt.Workbook() #创建一个工作簿
sheet = work.add_sheet(‘Hey, Hades’)#创建一个工作表sheet
sheet.write(0,0,‘money’) #在1行1列写入money
sheet.write(0,1,‘love’) #在1行2列写入love
sheet.write(1,0,‘python’) #在2行1列写入python
work.save(‘Test.xls’) #保存,文件名为Test


二、python实现代码及如下:

#-*- coding:utf-8 -*- 
import requests
import re
from bs4 import  BeautifulSoup
import xlwt
all_info_list=[]  #定义一个空列表,用来存储爬虫数据。
headers={'user-agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.74 Safari/537.36'}
def get_info(url):
    res=requests.get(url=url,headers=headers)
    soups=BeautifulSoup(res.text,'html.parser').find_all('h4')
    for soup in soups:
        infos=soup.find_all('a')
        for info in infos:
            course=re.findall(r'(?<=title=").*?(?=")',str(info))
            href=re.findall(r'(?<=href=").*?(?=")',str(info))
        info_list=[course,href]
        all_info_list.append(info_list)
if __name__=="__main__":
    urls=['https://ke.qq.com/course/list?mt=1001&st=2002&tt=3019&page={}'.format(i) for i in range(1,10)]#实现分页
    for url in urls:
        get_info(url)
    book=xlwt.Workbook(encoding='utf-8')
    sheet=book.add_sheet('kecheng')# 新增一个工作表,可传入表名
    head=['课程','连接']
    for h in range(len(head)):
        sheet.write(0,h,head[h])
        i=1
    for list in all_info_list:
        j=0
        for data in list:
            sheet.write(i,j,data)
            j+=1
        i+=1
    book.save('D:\file\kecheng.xls')

注意:以上代码是保存到D盘的file文件夹下的kecheng.xls。因此需要在D盘下的file文件下建一个excel表,表名为kecheng(D:\file\kecheng)

这个是运行以上代码之后,在D盘中的file文件夹打开课程,此时便存入到表中了,以下是部分的内容
在这里插入图片描述

感悟:
至从受到老师的启发,开始在博客上写一些自己所学习的、所做的、所想的、所领悟的,本来不想发朋友圈和动态的我不知道在哪里倾诉自己内心的想法,现在终于找到一个和大家一起分享学习的地方,使人快乐、轻松和愉悦,在此谢谢这位老师的启蒙,同时也谢谢这个csdn这个学习分享小天地!

Python爬取天气数据并保存到Excel文件(xls格式),通常需要几个步骤: 1. **选择天气API**:首先,你需要找到一个提供天气信息的API,比如中国气象局的API、OpenWeatherMap等。注册获取API密钥。 2. **安装库**:安装必要的库,如requests(用于发送HTTP请求)、BeautifulSoup(用于解析HTML)和pandas(处理数据和导出到Excel)。可以使用`pip install requests beautifulsoup4 pandas openpyxl`命令安装。 3. **编写代码**: ```python import requests from bs4 import BeautifulSoup import pandas as pd # 使用API密钥和URL构建请求 api_url = "https://your_weather_api.com/weather" headers = { 'Authorization': 'Bearer your_api_key', 'Content-Type': 'application/json' } def get_weather_data(): response = requests.get(api_url, headers=headers) data = response.json() # 提取所需的数据字段,例如城市名、日期和温度 city = data['city'] date = data['date'] temperature = data['temperature'] # 创建一个字典列表,存储每一天的天气信息 weather_list = [{'City': city, 'Date': date, 'Temperature': temperature}] return weather_list weather_data = get_weather_data() # 将数据转换为DataFrame df = pd.DataFrame(weather_data) # 导出为Excel文件(xls格式) df.to_excel('weather_data.xls', index=False) ``` **注意事项**: - API的具体使用方式和返回的数据结构可能会因服务而异,请查阅文档调整相应部分。 - 对于某些API,可能还需要对JSON数据进行适当的处理才能提取所需字段。 - 如果API返回的是CSV或其他格式,可能需要额外的转换步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值