网站的设计思路,怎么做自动发卡的网站,美食网站网站建设定位,自己名下备案的网站一、爬取豆瓣电影排行榜Top250存储到Excel文件 近年来#xff0c;Python在数据爬取和处理方面的应用越来越广泛。本文将介绍一个基于Python的爬虫程序#xff0c;用于抓取豆瓣电影Top250的相关信息#xff0c;并将其保存为Excel文件。 获取网页数据的函数#xff0c;包括以…一、爬取豆瓣电影排行榜Top250存储到Excel文件 近年来Python在数据爬取和处理方面的应用越来越广泛。本文将介绍一个基于Python的爬虫程序用于抓取豆瓣电影Top250的相关信息并将其保存为Excel文件。 获取网页数据的函数包括以下步骤1. 循环10次依次爬取不同页面的信息 2. 使用urllib获取html页面 3. 使用BeautifulSoup解析页面 4. 遍历每个div标签即每一部电影 5. 对每个电影信息进行匹配使用正则表达式提取需要的信息并保存到一个列表中 6. 将每个电影信息的列表保存到总列表中。 效果展示 源代码
from bs4 import BeautifulSoup
import re #正则表达式进行文字匹配
import urllib.request,urllib.error #指定URL获取网页数据
import xlwt #进行excel操作def main():baseurl https://movie.douban.com/top250?startdatalist getdata(baseurl)savepath .\\豆瓣电影top250.xlssavedata(datalist,savepath)#compile返回的是匹配到的模式对象
findLink re.compile(ra href(.*?)) # 正则表达式模式的匹配影片详情
findImgSrc re.compile(rimg.*src(.*?), re.S) # re.S让换行符包含在字符中,图片信息
findTitle re.compile(rspan classtitle(.*)/span) # 影片片名
findRating re.compile(rspan classrating_num propertyv:average(.*)/span) # 找到评分
findJudge re.compile(rspan(\d*)人评价/span) # 找到评价人数 #\d表示数字
findInq re.compile(rspan classinq(.*)/span) # 找到概况
findBd re.compile(rp class(.*?)/p, re.S) # 找到影片的相关内容如导演演员等##获取网页数据
def getdata(baseurl):datalist[]for i in range(0,10):url baseurlstr(i*25) ##豆瓣页面上一共有十页信息一页爬取完成后继续下一页html geturl(url)soup BeautifulSoup(html,html.parser) #构建了一个BeautifulSoup类型的对象soup是解析html的for item in soup.find_all(div,class_item): ##find_all返回的是一个列表data[] #保存HTML中一部电影的所有信息item str(item) ##需要先转换为字符串findall才能进行搜索link re.findall(findLink,item)[0] ##findall返回的是列表索引只将值赋值data.append(link)imgSrc re.findall(findImgSrc, item)[0]data.append(imgSrc)titlesre.findall(findTitle,item) ##有的影片只有一个中文名有的有中文和英文if(len(titles)2):onetitle titles[0]data.append(onetitle)twotitle titles[1].replace(/,)#去掉无关的符号data.append(twotitle)else:data.append(titles)data.append( ) ##将下一个值空出来rating re.findall(findRating, item)[0] # 添加评分data.append(rating)judgeNum re.findall(findJudge, item)[0] # 添加评价人数data.append(judgeNum)inq re.findall(findInq, item) # 添加概述if len(inq) ! 0:inq inq[0].replace(。, )data.append(inq)else:data.append( )bd re.findall(findBd, item)[0]bd re.sub(br(\s)?/(\s)?, , bd)bd re.sub(/, , bd)data.append(bd.strip()) # 去掉前后的空格datalist.append(data)return datalist##保存数据
def savedata(datalist,savepath):workbook xlwt.Workbook(encodingutf-8,style_compression0) ##style_compression0不压缩worksheet workbook.add_sheet(豆瓣电影top250,cell_overwrite_okTrue) #cell_overwrite_okTrue再次写入数据覆盖column (电影详情链接, 图片链接, 影片中文名, 影片外国名, 评分, 评价数, 概况, 相关信息) ##execl项目栏for i in range(0,8):worksheet.write(0,i,column[i]) #将column[i]的内容保存在第0行第i列for i in range(0,250):data datalist[i]for j in range(0,8):worksheet.write(i1,j,data[j])workbook.save(savepath)##爬取网页
def geturl(url):head {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36}req urllib.request.Request(url,headershead)try: ##异常检测response urllib.request.urlopen(req)html response.read().decode(utf-8)except urllib.error.URLError as e:if hasattr(e,code): ##如果错误中有这个属性的话print(e.code)if hasattr(e,reason):print(e.reason)return htmlif __name__ __main__:main()print(爬取成功) 二、爬取百度热搜排行榜Top50可视化 2.1 代码思路
导入所需的库
import requests
from bs4 import BeautifulSoup
import openpyxlBeautifulSoup 库用于解析HTML页面的内容。 openpyxl 库用于创建和操作Excel文件。 2.发起HTTP请求获取百度热搜页面内容
url https://top.baidu.com/board?tabrealtime
response requests.get(url)
html response.content 这里使用了 requests.get() 方法发送GET请求并将响应的内容赋值给变量 html。 3.使用BeautifulSoup解析页面内容
soup BeautifulSoup(html, html.parser) 创建一个 BeautifulSoup 对象并传入要解析的HTML内容和解析器类型。 4.提取热搜数据
hot_searches []
for item in soup.find_all(div, {class: c-single-text-ellipsis}):hot_searches.append(item.text) 这段代码通过调用 soup.find_all() 方法找到所有 div 标签并且指定 class 属性为 c-single-text-ellipsis 的元素。 然后将每个元素的文本内容添加到 hot_searches 列表中。 5.保存热搜数据到Excel
workbook openpyxl.Workbook()
sheet workbook.active
sheet.title Baidu Hot Searches 使用 openpyxl.Workbook() 创建一个新的工作簿对象。 调用 active 属性获取当前活动的工作表对象并将其赋值给变量 sheet。 使用 title 属性给工作表命名为 Baidu Hot Searches。 6.设置标题
sheet.cell(row1, column1, value百度热搜排行榜—博主:郭wes代码) 使用 cell() 方法选择要操作的单元格其中 row 和 column 参数分别表示行和列的索引。 将标题字符串 百度热搜排行榜—博主:郭wes代码 写入选定的单元格。 7.写入热搜数据
for i in range(len(hot_searches)):sheet.cell(rowi2, column1, valuehot_searches[i]) 使用 range() 函数生成一个包含索引的范围循环遍历 hot_searches 列表。 对于每个索引 i使用 cell() 方法将对应的热搜词写入Excel文件中。 8.保存Excel文件
workbook.save(百度热搜.xlsx) 使用 save() 方法将工作簿保存到指定的文件名 百度热搜.xlsx。 9.输出提示信息
print(热搜数据已保存到 百度热搜.xlsx) 在控制台输出保存成功的提示信息。 源代码 import requests
from bs4 import BeautifulSoup
import openpyxl# 发起HTTP请求获取百度热搜页面内容
url https://top.baidu.com/board?tabrealtime
response requests.get(url)
html response.content# 使用BeautifulSoup解析页面内容
soup BeautifulSoup(html, html.parser)# 提取热搜数据
hot_searches []
for item in soup.find_all(div, {class: c-single-text-ellipsis}):hot_searches.append(item.text)# 保存热搜数据到Excel
workbook openpyxl.Workbook()
sheet workbook.active
sheet.title Baidu Hot Searches# 设置标题
sheet.cell(row1, column1, value百度热搜排行榜—博主:郭wes代码)# 写入热搜数据
for i in range(len(hot_searches)):sheet.cell(rowi2, column1, valuehot_searches[i])workbook.save(百度热搜.xlsx)
print(热搜数据已保存到 百度热搜.xlsx) 可视化代码 import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt# 发起HTTP请求获取百度热搜页面内容
url https://top.baidu.com/board?tabrealtime
response requests.get(url)
html response.content# 使用BeautifulSoup解析页面内容
soup BeautifulSoup(html, html.parser)# 提取热搜数据
hot_searches []
for item in soup.find_all(div, {class: c-single-text-ellipsis}):hot_searches.append(item.text)# 设置中文字体
plt.rcParams[font.sans-serif] [SimHei]
plt.rcParams[axes.unicode_minus] False# 绘制条形图
plt.figure(figsize(15, 10))
x range(len(hot_searches))
y list(reversed(range(1, len(hot_searches)1)))
plt.barh(x, y, tick_labelhot_searches, height0.8) # 调整条形图的高度# 添加标题和标签
plt.title(百度热搜排行榜)
plt.xlabel(排名)
plt.ylabel(关键词)# 调整坐标轴刻度
plt.xticks(range(1, len(hot_searches)1))# 调整条形图之间的间隔
plt.subplots_adjust(hspace0.8, wspace0.5)# 显示图形
plt.tight_layout()
plt.show() 三、爬取酷狗音乐Top500排行榜 从酷狗音乐排行榜中提取歌曲的排名、歌名、歌手和时长等信息
总体思路 import requests # 发送网络请求获取 HTML 等信息
from bs4 import BeautifulSoup # 解析 HTML 信息提取需要的信息
import time # 控制爬虫速度防止过快被封IPheaders {User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36# 添加浏览器头部信息模拟请求
}def get_info(url):# 参数 url 要爬取的网页地址web_data requests.get(url, headersheaders) # 发送网络请求获取 HTML 等信息soup BeautifulSoup(web_data.text, lxml) # 解析 HTML 信息提取需要的信息# 通过 CSS 选择器定位到需要的信息ranks soup.select(span.pc_temp_num)titles soup.select(div.pc_temp_songlist ul li a)times soup.select(span.pc_temp_tips_r span)# for 循环遍历每个信息并将其存储到字典中for rank, title, time in zip(ranks, titles, times):data {rank: rank.get_text().strip(), # 歌曲排名singer: title.get_text().replace(\n, ).replace(\t, ).split(-)[1], # 歌手名song: title.get_text().replace(\n, ).replace(\t, ).split(-)[0], # 歌曲名time: time.get_text().strip() # 歌曲时长}print(data) # 打印获取到的信息if __name__ __main__:urls [https://www.kugou.com/yy/rank/home/{}-8888.html.format(str(i)) for i in range(1, 24)]# 构造要爬取的页面地址列表for url in urls:get_info(url) # 调用函数获取页面信息time.sleep(1) # 控制爬虫速度防止过快被封IP