爬虫介绍/准备工作/构建流程/获取数据/BeautifulSoup/Re(正则表达式)/正则提取/标签解析/保存数据到excel
更新时间:.9.16
vedio:15,16,17,18,19,20,21,22,23,24,25*
# -*- coding: utf-8 -*-# @Time : /9/4 18:33# @Author : 李新宇# @FileName: t1.py# @Software: PyCharmdef add(a,b):return a+bprint(add(2,3))
# -*- coding: utf-8 -*-# @Time : /9/4 18:33# @Author : 李新宇# @FileName: t2.py# @Software: PyCharmfrom test1 import t1#引入自定义模块print(t1.add(2,3))#引入系统模块import osimport sys#引入·第三方模块import re
# -*- coding: utf-8 -*-# @Time : /9/9 10:56# @Author : 李新宇# @FileName: testXwlt.py# @Software: PyCharmimport xlwt'''workbook = xlwt.Workbook(encoding="utf-8") #创建workbook对象worksheet = workbook.add_sheet('sheet1') #创建工作表worksheet.write(0,0,'hello') #写入数据,第一个参数“行”,第二个参数“列”,第三个参数内容workbook.save('studen.xls') #保存数据表'''#99乘法表workbook = xlwt.Workbook(encoding="utf-8") #创建workbook对象worksheet = workbook.add_sheet('sheet1') #创建工作表for i in range(0,9):for j in range(0,i+1):worksheet.write(i,j,"%d * %d = %d"%(i+1,j+1,(i+1)*(j+1)))workbook.save('studen.xls') #保存数据表
# -*- coding: utf-8 -*-# @Time : /9/4 19:12# @Author : 李新宇# @FileName: testUrllib.py# @Software: PyCharmimport urllib.request'''#获取一个get请求response = urllib.request.urlopen("")print(response.read().decode('utf-8')) #对获取到的网页源码进行utf-8的解码#获取一个post请求''''''import urllib.parsedata = bytes(urllib.parse.urlencode({"hello":"world"}),encoding='utf-8')response = urllib.request.urlopen("/post",data= data )print(response.read().decode('utf-8'))'''#获取一个get请求'''try:response = urllib.request.urlopen("/get",timeout=3)print(response.read().decode('utf-8'))except urllib.error.URLError as e:print("time out")''''''response = urllib.request.urlopen("")#print(response.status)print(response.getheaders())'''# url = ""'''url = "/post"headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38"}data = bytes(urllib.parse.urlencode({'name':'eric'}),encoding="utf-8")req = urllib.request.Request(url=url,data=data,headers=headers,method="POST")response = urllib.request.urlopen(req)print(response.read().decode('utf-8'))'''url = ""headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38"}req = urllib.request.Request(url=url,headers=headers)response = urllib.request.urlopen(req)print(response.read().decode("utf-8"))
# -*- coding: utf-8 -*-# @Time : /9/7 21:04# @Author : 李新宇# @FileName: testBs4.py# @Software: PyCharmimport refrom bs4 import BeautifulSoupfile = open("./baidu.html","rb")html = file.read().decode("utf-8")bs = BeautifulSoup(html,"html.parser")#print(bs.title)#print(bs.a)#print(type(bs.head))#1.tag 标签及其内容:拿到他所找到的第一个内容'''print(bs.title.string)print(type(bs.title.string))#NavigableString 标签里的内容(字符串)'''#print(bs.a.attrs)#attrs属性#print(type(bs))#3.BeautifulSoup: 表示整个文档#print(bs)## print(bs.a.string)# print(type(bs.a.string))#mment 是一个特殊的NavigableString ,输出的内容不包含注释符号#---------------------------------#文档的遍历#print(bs.head.contents)#print(bs.head.contents[1])#更多内容,搜索文档#文档的搜索#find_all()#字符串过滤:会查找与字符串完全匹配的内容#t_list = bs.find_all("a")import re#正则表达式搜索:使用serach()方法来匹配内容#t_list = bs.find_all(pile("a"))#方法 :传入一个函数(方法),根据函数的方法要求来搜索(了解)'''def name_is_exists(tag):return tag.has_attr("name")t_list = bs.find_all(name_is_exists)for item in t_list:print(item)#print(t_list)'''#2.kwargs 参数#t_list = bs.find_all(id="head")# t_list = bs.find_all(class_="True")## for item in t_list:#print(item)#3.text文本# t_list = bs.find_all(text="hao123")#t_list = bs.find_all(text=["hao123","地图","贴吧"])#t_list = bs.find_all(text=pile("\d")) #应用正则表达式来查找包含特定文本的内容(标签里的字符串)#4.limit参数# t_list = bs.find_all("a",limit=3)## for item in t_list:#print(item)##4.css选择器#t_list = bs.select("title") #通过标签来查找#t_list = bs.select(".mnav") #通过类名来查找#t_list = bs.select("#u1") #通过id来查找#t_list = bs.select("a[class='bri']") #通过属性来查找#t_list = bs.select("head > title") #通过子标签来查找# t_list = bs.select(".mnav ~ .bri")# print(t_list[0].get_text())# for item in t_list:# print(item)
# -*- coding: utf-8 -*-# @Time : /9/8 16:05# @Author : 李新宇# @FileName: testre.py# @Software: PyCharm#正则表达式: 字符串模式 (判断字符串是否符合一定的标准)import re#创建模式对象pat = pile("AA") #此处的aa是正则表达式,用来验证其他的字符串#m = pat.search("BBBBCCAA") #search后字符串被检验的内容#m = pat.search("BBAABBCCAA") #search方法进行查找,比对#没有模式对象# m = re.search("asd","asdd") #前面的字符串是规则(模板),后面的字符串是被校验的对象# print(m)#print(re.findall("a","asdaddddaa")) #前面字符串是规则(正则表达式),后面字符串是被校验的字符串#print(re.findall("[a-z]","AAasdaddddaa"))#print(re.findall("[a-z]+","AAsAdadddAAdaa"))#subprint(re.sub("a","A","abcdcasd")) #找到a用A替换,在第三个字符串中查找,substitute#建议在正则表达式中,被比较的字符串前面加上r,不用担心转义字符的问题a = r"\aabd-\'"print(a)
# -*- coding: utf-8 -*-# @Time : /9/9 16:18# @Author : 李新宇# @FileName: testsqlite.py# @Software: PyCharmfrom bs4 import BeautifulSoup # 网页解析,获取数据import re # 正则表达式,进行文字匹配import urllib.request, urllib.error # 制定URL,获取网页数据import xlwt # 进行excel操作def main():baseurl = "/top250?start="# 1.爬取网页datalist = getData(baseurl)savepath = "豆瓣电影Top250.xls"# 3.保存数据saveData(datalist,savepath)# askURL("/top250?start=")# 影片详情链接的规则findLink = pile(r'<a href="(.*?)">') # 创建正则表达式对象,表示规则(字符串的模式)# 影片图片findImgSrc = pile(r'<img.*src="(.*?)"', re.S) # re.S 让换行符包含在字符中# 影片片名findTitle = pile(r'<span class="title">(.*)</span>')# 影片评分findRating = pile(r'<span class="rating_num" property="v:average">(.*)</span>')# 找到评价人数findJudge = pile(r'<span>(\d*)人评价</span>')# 找到概况findInq = pile(r'<span class="inq">(.*)</span>')# 找到影片的相关内容findBd = pile(r'<p class="">(.*?)</p>', re.S)# 爬取网页def getData(baseurl):datalist = []for i in range(0, 10): # 调用获取页面信息的函数,10次url = baseurl + str(i * 25)html = askURL(url) # 保存获取到的网页源码# 2.逐一解析数据soup = BeautifulSoup(html, "html.parser")for item in soup.find_all('div', class_="item"): # 查找符合要求的字符串,形成列表# print(item) #测试:查看电影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)otitle = titles[1].replace("/", "") # 去掉无关的符号data.append(otitle) # 添加外国名else:data.append(titles[0])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) # 去掉<br/>bd = re.sub('/', " ", bd) # 替换/data.append(bd.strip()) # 去掉前后的空格datalist.append(data) # 把处理好的一部电影信息放入datalist#print(datalist)return datalist# 得到指定一个URL的网页内容def askURL(url):head = {# 模拟浏览器头部信息,向豆瓣服务器发送消息"User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122 Safari / 537.36"}# 用户代理,表示告诉豆瓣服务器,我们是什么类型的机器、浏览器(本质上是告诉浏览器,我们可以接收什么水平的文件内容)request = urllib.request.Request(url, headers=head)html = ""try:response = urllib.request.urlopen(request)html = response.read().decode("utf-8")# print(html)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):print("save....")book = xlwt.Workbook(encoding="utf-8", style_compression=0) # 创建workbook对象sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) # 创建工作表col = ("电影详情链接", "图片链接", "影片中文名", "影片外国名", "评分", "评价数", "概况", "相关信息")for i in range(0, 8):sheet.write(0, i, col[i]) # 列名for i in range(0, 250):print("第%d条" % (i + 1))data = datalist[i]for j in range(0, 8):sheet.write(i + 1, j, data[j]) # 数据book.save(savepath) # 保存if __name__ == "__main__": # 当程序执行时# 调用函数main()print("爬取完毕!")
【6】爬虫介绍/准备工作/构建流程/获取数据/BeautifulSoup/Re(正则表达式)/正则提取/标签解析/保存数据到excel
如果觉得《【6】爬虫介绍/准备工作/构建流程/获取数据/BeautifulSoup/Re(正则表达式)/正则提取/》对你有帮助,请点赞、收藏,并留下你的观点哦!