python学习——爬取数据到excel

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()

爬取的效果是这样的

 

posted on 2022-10-15 19:58  跨越&尘世  阅读(800)  评论(0编辑  收藏  举报