首页 > 编程语言 >python学习——爬取数据到excel

python学习——爬取数据到excel

时间:2022-10-15 20:13:14浏览次数:53  
标签:item python excel 爬取 re html data append

python的学习直接使用网页爬虫,将内容爬取到excel,也是为之后的大数据学习做铺垫。

下面的代码是我爬取的豆瓣电影Top250的电影基本信息,当然,也可以爬取到数据库中

# -*- coding:utf-8 -*-  
# 上面这一行的目的是防止乱码
from bs4 import BeautifulSoup # 数据解析,处理html import re # 正则表达式 import urllib.request, urllib.error import xlwt # 进行excel操作 def main(): baseurl = "https://movie.douban.com/top250?start=" # 1、爬取网页 datalist = getData(baseurl) # 3、保存数据 savepath = "C:\\Users\\Jzz\\Desktop\\python\\豆瓣电影top250.xls" saveData(datalist, savepath) # 影片链接 findlink = re.compile(r'<a href="(.*?)">') # 创建正则表达式对象,表示规则 # 影片图片链接 findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S) # re.S使换行符包含在字符中 # 片名 findTitle = re.compile(r'<span class="title">(.*?)</span>') # 影片评分 findRate = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>') # 评价人数 findJudge = re.compile(r'<span>(\d*)人评价</span>') # 概况 findIng = re.compile(r'<span class="inq">(.*)</span>') # 找到影片内容 findBd = re.compile(r'<p class="">(.*?)</p>', re.S) # 爬取网页 def getData(baseurl): datalist = [] for i in range(0, 10): url = baseurl + str(i * 25) html = askUrl(url) # 逐一解析数据 soup = BeautifulSoup(html, "html.parser") for item in soup.find_all('div', class_="item"): # 查找符合要求的字符串 data = [] # 保存一部电影所有信息,列表 item = str(item) # 影片链接 link = re.findall(findlink, item)[0] # re库通过正则表达式查找指定字符串 data.append(link) imgSrc = re.findall(findImgSrc, item)[0] data.append(imgSrc) titles = re.findall(findTitle, item) # 片名可能只有一个中文名 if (len(titles) == 2): ctitle = titles[0] data.append(ctitle) ftitle = titles[1].replace("/", "") data.append(ftitle) else: data.append(titles[0]) data.append(' ') # 外文名留空 rate = re.findall(findRate, item)[0] data.append(rate) judge = re.findall(findJudge, item)[0] data.append(judge) ing = re.findall(findIng, item) if (len(ing) != 0): ing = ing[0].replace("。", "") data.append(ing) else: data.append(' ') bd = re.findall(findBd, item)[0] bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd) # 去掉<br/> bd = re.sub('/', " ", bd) data.append(bd.strip()) # 去掉空格 datalist.append(data) return datalist # 得到指定网页的内容 def askUrl(url): # 模拟浏览器头部 head = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"} request = urllib.request.Request(url, headers=head) html = "" try: response = urllib.request.urlopen(request) 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 html def saveData(datalist, savepath): workbook = xlwt.Workbook(encoding="utf-8", style_compression=0) worksheet = workbook.add_sheet("豆瓣电影Top250", cell_overwrite_ok=True) col = ('电影链接', "图片链接", "影片中文名", "影片别名", "评分", "评价", "概况", "相关信息") for i in range(0, 8): worksheet.write(0, i, col[i]) for i in range(0, 250): print("第%d条" % i) data = datalist[i] for j in range(0, 8): worksheet.write(i + 1, j, data[j]) workbook.save(savepath) if __name__ == '__main__': # python的main函数 main()

爬取的效果是这样的

 

标签:item,python,excel,爬取,re,html,data,append
From: https://www.cnblogs.com/jzz-111jy/p/16794928.html

相关文章

  • 爬取spa网站与ssr网站的区别
    前言在练习爬虫的时候不清楚spa与ssr网站的区别,都使用bs4直接解析网页的html,结果ssr网站输出结果,spa网站却没有输出结果,特此记录ssr网站:https://ssr1.scrape.center/page......
  • (数据科学学习手札144)使用管道操作符高效书写Python代码
    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes1简介大家好我是费老师,一些比较熟悉pandas的读者朋友应该经常会使用que......
  • python 笔记
    变量:直接弄,不用搞类型,关于字符串有一个转义/的运用.注释:#(单行)''''''多行python没有{},用行对齐来表示函数:def+函数名(参数): 加回车下面就开始......
  • Python-excel转置,行转列,列转行
    代码importpandasaspddf=pd.read_excel('temp.xlsx',index=False)#读取需要转置的文件df=df.T#转置#df.to_excel('abc.xlsx',header=False)#另存为x......
  • python 中OS操作
    #获取系统名称In[235]:os.nameOut[235]:'nt'#win系统的名称nt#获取当前文件的绝对路径In[236]:os.getcwd()Out[236]:'D:\\djangoPro\\sample\\1''''绝对路径:从具......
  • python第十五课--近期代码练习
    1.利用有参装饰器编写多种用户登录校验策略"""1.直接写死的jason1232.数据来源于列表['jason|123','kevin|321','tony|222']3.数据来源于文件jason|123\ntom|32......
  • 力扣454(java&python)-四数相加 II(中等)
    题目:给你四个整数数组nums1、nums2、nums3和nums4,数组长度都是n,请你计算有多少个元组(i,j,k,l)能满足:0<=i,j,k,l<nnums1[i]+nums2[j]+nums3[k]+......
  • 在docker应用中安装python3环境,运行程序,输出日志时间比本地时间慢8小时
    根据排查原因是docker容器时间以0时区为准,中国在东8区,因此输出时间比中国时间慢了8小时解决方法一:1:首先,进入docker应用中dockerexec-it-urootjenkinsbash说明:使......
  • python3.10新特性
    python3.10新特性1.指定1个或多个属性类型.deffunc(num:int|float|str):print(num)func(['a',])#当传入参数与要求不符时,会给予提示2.更严格zip()......
  • iframe 在线预览pdf、word、excel、ppt、txt、图片、视频
    第一种方式通过iframe在线预览pdf,word,excel,ppt,txt,图片,视频<template><el-button@click="openHandler">预览</el-button><el-dialog@close="closeHa......