第八周总结
正则解析红牛分公司
import re import requests res = requests.get('http://www.redbull.com.cn/about/branch') s = res.text name = re.findall("data-title='(.*?)'",s) place = re.findall("data-describe='(.*?)'",s) email = re.findall("<p class='mailIco'>(.*?)</p>",s) phone = re.findall("<p class='telIco'>(.*?)</p>",s) for i in range(len(name)): print('公司名称:%s' '公司地址:%s' '公司邮编:%s' '公司电话:%s'% (name[i],place[i],email[i],phone[i]))
爬取糗图百科图片数据
import requests from bs4 import BeautifulSoup import os if not os.path.exists(r'糗图图片'): os.mkdir(r'糗图图片') def get_img(url): # 1.发送get请求获取页面数据 res = requests.get(url) # 2.解析库bs4 soup = BeautifulSoup(res.text, 'lxml') # 3.研究标签特征 获取图片链接 img_tag_list = soup.find_all(name='img', attrs={'class': 'illustration'}) for img in img_tag_list: img_src = img.get('src') full_src = 'https:' + img_src # 朝图片完整的地址发送请求保存数据 res1 = requests.get(full_src) img_name = full_src.rsplit('/')[-1] file_path = os.path.join(r'糗图图片', img_name) with open(file_path, 'wb') as f: f.write(res1.content) print('图片:%s 保存成功' % img_name) for i in range(1, 5): base_url = "https://www.qiushibaike.com/imgrank/page/%s/" % i get_img(base_url)
import requests from bs4 import BeautifulSoup import os # 引用模块 if not os.path.exists(r'优美图片库'): os.mkdir(r'优美图片库') # 查看本地是否存在优美图片库文件夹,如果没有则创建 res = requests.get('https://www.umei.cc/bizhitupian/fengjingbizhi/') # 获取网页数据 res.encoding = 'utf-8' # 确认一下编码的类型 soup = BeautifulSoup(res.text, 'lxml') # 选定筛选的范围 div_tag = soup.find(name='div', attrs={'class': 'TypeList'}) # 筛选class为TypeList的div代码 li_list = div_tag.find_all(name='li') # 找到div中的li字段 for li in li_list: # 循环取出每一条li字段 a_tag = li.find(name='a') # 筛选出每一条li中的a字段 a_link = a_tag.get('href') # 获取每一条a字段中的href a_full_link = 'https://www.umei.cc' + a_link # 把href拼接成正确的网页 res1 = requests.get(a_full_link) # 从新网页获取数据 soup1 = BeautifulSoup(res1.text, 'lxml') # 选定筛选的范围 img_tag = soup1.select('div.ImageBody img') # 筛选class为ImageBody的div代码中的img代码 for img in img_tag: # 循环取出img代码 src = img.get('src') # 获取img代码中的src字段 res2 = requests.get(src) # 通过src获取图片数据 file_path = os.path.join(r'优美图片库', src.rsplit('/')[-1]) # 给图片取名字,并路径拼接到优美图片库文件夹中 with open(file_path, 'wb') as f: f.write(res2.content) # 把从网页获取的图片数据写入优美图片库中 print('图片:%s 下载成功' % file_path)
import requests from bs4 import BeautifulSoup import os import time if not os.path.exists(r'梨视频数据'): os.mkdir(r'梨视频数据') def get_video(n): res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=31&start=%s' % n) soup = BeautifulSoup(res.text, 'lxml') li_list = soup.select('li.categoryem') for li in li_list: a_tag = li.find(name='a') a_href_link = a_tag.get('href') # video_1742158 video_id = a_href_link.split('_')[-1] headers = { "Referer": "https://www.pearvideo.com/video_%s" % video_id } res1 = requests.get('https://www.pearvideo.com/videoStatus.jsp', params={'contId': video_id}, headers=headers ) data_dict = res1.json() src_url = data_dict['videoInfo']['videos']['srcUrl'] systemTime = data_dict['systemTime'] # https://video.pearvideo.com/mp4/adshort/20210920/1632285084621-15771122_adpkg-ad_hd.mp4 real_url = src_url.replace(systemTime, 'cont-%s' % video_id) res2 = requests.get(real_url) file_path = os.path.join(r'梨视频数据', '%s.mp4' % video_id) with open(file_path, 'wb') as f: f.write(res2.content) time.sleep(0.5) for n in range(12, 48, 12): get_video(n)
校验当前请求从何而来 如果是本网站则允许访问如果是其他网址则拒绝 在请求头中有一个专门用于记录从何而来的键值对 referer建
创建文件
(在使用openpyxl模块操作excel文件的时候一定要确保文件是关闭状态)
from openpyxl import Workbook
1.创建一个对象
wb = Workbook()
3.创建多个工作簿
wb1 = wb.create_sheet('学生表') wb2 = wb.create_sheet('课程表')
4.还可以指定工作簿的顺序
w3 = wb.create_sheet('老师表',0)
5.create_sheet方法会返回当前被创建的工作簿对象
w3.title = '教师表' # 工作簿名称支持二次修改 w3.sheet_properties.tabColor = "1072BA "# 修改工作簿名称样式 print(wb.sheetnames) # 查看当前excel文件所有的工作簿名称
2.保存文件
wb.save(r'1.xlsx')
如何写数据
from openpyxl import Workbook wb = Workbook() wb1 = wb.create_sheet('数据统计',0)
写入数据方式1
wb1['A1'] = 111 wb1['A2'] = 222
写入数据方式2
wb1.cell(column=1,row=3,value=333) # cell意思是单元格
写入数据方式3
wb1.append(['序号', '姓名', '年龄', '性别']) # 定义表头数据 wb1.append([1, 'jason', 28, 'male']) # 存储表单数据 wb1.append([2, 'tony', 38, 'female']) # 存储表单数据 wb1.append([3, 'kevin', 28, 'male']) # 存储表单数据 wb1.append([4, 'kevin1', 'male']) # 存储表单数据 wb1.append([5, 'kevin2', 'female']) # 存储表单数据 wb1.append([5, 'kevin2', '', 'female']) # 存储表单数据 wb1.append([5, 'kevin2', 88, None]) # 存储表单数据
(append是按照行数一行行录入数据)
写入计算公式
wb1["A9"] = '=sum(A2:A8)'
wb.save(r'2.xlsx')
如何读数据
from openpyxl import load_workbook
1.指定要读取的表格文件
wb = load_workbook(r'2.xlsx',data_only=True)
2.先查看工作簿名称,并指定你要操作的工作簿
print(wb.sheetnames) # ['数据统计','Sheet']
3.指定操作的工作簿
wb1 = wb['数据统计'] # wb1指代的就是数据统计的工作簿
读取数据的方式1
print(wb1['B2'].value) # 获取普通数据 print(wb1['A9'].value) # 获取公式 =SUM(A2:A8)
如果在读取数据的时候不想获取公式本身而是公式的结果需要指定data_only参数
wb = load_workbook(r'2.xlsx',data_only=True)
读取数据的方式2
print(wb1.cell(row=3,column=2).value) for row in wb1.rows: for r in row: print(r.value) for col in wb1.columns: for c in col: print(c.value)
获取最大的行数和列数
print(wb1.max_row) print(wb1.max_column)
1.先研究单页数据的爬取
2.再研究多页数据的爬取
3.最后研究如何写入文件
(一定要将复杂的功能拆分成多个简单的小步骤
2,3步骤可以交换顺序,可能更简单)
前戏:发现一些小规律
https://sh.lianjia.com/ershoufang/
省市
https://sh.lianjia.com/ershoufang/pudong/
区
需求分析:
名称,地址,详细信息,关注人数,发布时间,单价,总价
多页分析:
第一页:https://sh.lianjia.com/ershoufang/pudong/
第二页:https://sh.lianjia.com/ershoufang/pudong/pg2/
第三页:https://sh.lianjia.com/ershoufang/pudong/pg3/
import requests from bs4 import BeautifulSoup from openpyxl import Workbook wb = Workbook() wb1 = wb.create_sheet('二手房数据') # 先定义表头 wb1.append(['房屋名称', '详情链接', '小区名称', '区域名称', '详细信息', '关注人数', '发布时间', '总价', '单价']) def get_info(num): # 1.经过分析得知页面数据直接加载 res = requests.get('https://sh.lianjia.com/ershoufang/pudong/pg%s/' % num) # print(res.text) # 2.查看是否有简单的防爬以及页面编码问题 # 3.利用解析库筛选数据 soup = BeautifulSoup(res.text, 'lxml') # 4.分析数据特征 采取相应解析措施 # 先整体后局部 先查找所有li标签 li_list = soup.select('ul.sellListContent>li') # 然后循环获取每一个li标签 再去内部筛选一个个数据 for li in li_list: # 依次获取所需数据 select与findall返回的结果都是列表 find返回的是标签对象 a_tag = li.select('div.title>a')[0] # 房屋名称 title = a_tag.text # 详情链接 link = a_tag.get('href') div_tag = li.select('div.positionInfo')[0] # 地址信息 address = div_tag.text # xxx - xxx res = address.split('-') if len(res) == 2: xq_name, xq_pro = res else: xq_name = xq_pro = res[0] div_tag1 = li.select('div.houseInfo')[0] # 详细信息 # TODO:该项数据也可以做详细拆分 并且需要考虑缺失情况 info = div_tag1.text div_tag2 = li.select('div.followInfo')[0] # 关注度及发布时间 focus_time = div_tag2.text # xxx / xxx people_num, publish_time = focus_time.split('/') div_tag3 = li.select('div.totalPrice')[0] # 总价 total_price = div_tag3.text div_tag4 = li.select('div.unitPrice')[0] # 单价 unit_price = div_tag4.text wb1.append( [title, link, xq_name.strip(), xq_pro.strip(), info, people_num.strip(), publish_time.strip(), total_price, unit_price]) for i in range(1, 5): get_info(i) wb.save(r'二手房数据.xlsx')
爬取汽车之家新闻数据
需求分析:
获取新闻数据:
新闻标题,新闻链接,新闻图标,发布时间,新闻简介
特性分析:
1.页面数据也存在动态加载,但是该动态加载是由js代码完成
(第一次请求数据的时候其实就已经获取到了所有的数据,只不过是通过js代码控制展示条数的)
2.页面干扰项
(没有实际作用的代码,只是夹杂在正常代码里防止被轻易爬取)
import time import requests from bs4 import BeautifulSoup from openpyxl import Workbook wb = Workbook() wb1 = wb.create_sheet('汽车之家') wb1.append(['详情链接', '新闻标题', '新闻图标', '发布时间', '新闻简介', '观看次数', '评论次数']) for n in range(1): res = requests.get('https://www.autohome.com.cn/news/%s/#liststart'%n, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" } ) res.encoding = 'gbk' soup = BeautifulSoup(res.text, 'lxml') # 1.先查找所有的li标签 li_list = soup.select("ul.article>li") # 2.循环li标签 获取内部所需数据 for li in li_list: a_tag = li.find('a') if not a_tag: # 当该标签内部无法获取到其他标签时 说明往下再获取其他标签就没有意义了 continue # 新闻详情页链接 link = 'https:' + a_tag.get('href') h3_tag = li.find('h3') if not h3_tag: continue # 获取新闻标题 title = h3_tag.text img_tag = li.find('img') if not img_tag: continue # 获取新闻图标 src = img_tag.get('src') span_tag = li.find('span') if not span_tag: continue # 获取发布时间 publish_time = span_tag.text p_tag = li.find('p') if not p_tag: continue # 获取文字简介 desc = p_tag.text em_tag = li.find('em') if not em_tag: continue # 获取观看次数 watch_num = em_tag.text em1_tag = li.find('em',attrs={'data-class': 'icon12 icon12-infor'}) if not em1_tag: continue # 获取评论次数 comment_num = em1_tag.text wb1.append([link,title,src,publish_time,desc,watch_num,comment_num]) time.sleep(1) wb1.save(r'汽车之家.xlsx')