当前位置:网站首页>爬虫小白笔记(昨天的对于注意解析数据的补充)
爬虫小白笔记(昨天的对于注意解析数据的补充)
2022-08-04 15:25:00 【总是汗水大过天赋】
import re
import urllib.request
from bs4 import BeautifulSoup
def main():
#1.抓取网页(在这里面逐一解析数据)
baseurl = 'https://movie.douban.com/top250?start='
datalist = getData(baseurl)
#2.保存数据
print()
#电影链接
findLink = re.compile(r'<a href="(.*?)">')
#电影图片
findImg = re.compile(r'<img.*src="(.*?)"',re.S)#re.S表示匹配成功的字符里面可以忽略空格(当你想要的内容里面有许多空格,你想要它里面出来没有空格时使用)
#影片片名
findTitle = re.compile(r'<span class="title">(.*?)</span>')
#影片评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')
#概况
findInq = re.compile(r'<span class="inq">(.*?)</span>')
#影片相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#抓取网页
def getData(baseurl):
#首先需要获取一页的数据,然后利用循环来获取每一页的信息
#datalist每一个存储一页数据
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]
data.append(link)
img = re.findall(findImg,item)[0]
data.append(img)
title = re.findall(findTitle,item)
if(len(title) == 2) :
ctitle = title[0]
data.append(ctitle)
etitle = title[1].replace("/","")
data.append(etitle)
else:
data.append(title[0])
data.append(' ')#当不存在英文名字时,用空格把位置留着
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)#把处理好的一部电影信息放入datalist里面
print(datalist)
return datalist
#请求网页
def askURL(url):
header = {
"User-Agent":"Mozilla/5.0(Linux;Android6.0;Nexus5 Build / MRA58N) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 103.0.5060.134MobileSafari / 537.36Edg / 103.0.1264.77"
}
request = urllib.request.Request(url,headers = header)
html = ""
try :
responce = urllib.request.urlopen(request)
html = responce.read().decode()
except urllib.error.URLerror as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
#保存数据
def saveData() :
print()
if __name__ == '__main__':
main()边栏推荐
猜你喜欢
随机推荐
Byte、Short、Integer、Long内部缓存类的对比与源码分析
Legal education combined with VR panorama, intuitively feel and learn the spirit of the rule of law
H5 开发内嵌页面跨域问题
学 Go,最常用的技能是什么?打日志
postman “header“:{“retCode“:“999999“
Roslyn 通过 nuget 统一管理信息
IP第十六天笔记
Go 事,Gopher 要学的数字类型,变量,常量,运算符 ,第2篇
LeetCode_模拟_中等_498.对角线遍历
界面组件DevExpress ASP.NET Core v22.1 - 增强数据导出功能
性能提升400倍丨外汇掉期估值计算优化案例
Go Go 简单的很,标准库之 fmt 包的一键入门
Latex 去掉行号
Redis-哨兵模式
PTA 6-2 多项式求值
手搓一个“七夕限定”,用3D Engine 5分钟实现烟花绽放效果
什么,你告诉我?作用域也分种类?
什么是 DevOps?看这一篇就够了!
7 天能找到 Go 工作吗?学学 Go 数组和指针试试
普法教育结合VR全景,直观感受和学习法治精神









