爬虫之爬图片和视频:
一、爬图片:
# 导入模块包 import requests import re # 链接地址 url = "https://www.hellorf.com/image/search?q=%E7%A7%91%E6%8A%80&source=bd" # 获取网页信息 response = requests.get(url) res = response.text # print(res) # 清洗数据,把图片链接提取出来 one_data = re.findall('''img data-src="(.*?)"''', res) for i in one_data: image_response = requests.get(i) # 获取图片,得到二进制数据 image_data = image_response.content # 对二进制数据进行清洗,得到图片的名称 img_name = i.split('/')[-1] # print(img_name) # 拿到二进制数据 f = open(img_name, 'wb') f.write(image_data) f.flush() # 快速刷新
二、爬视频
# 导入模块包 import requests import re # 获取链接,爬取网站,清洗数据 url = 'http://www.mod.gov.cn/v/2019-07/24/content_4846365.htm' response = requests.get(url) data = response.text # print(data) mp4_url = re.findall('//Video (.*?).mp4', data) # 拼接数据,得到完整url mp4_str = mp4_url[0] + '.mp4' # 进入mp4的url mp4_data = requests.get(mp4_str) # 拿到视频的二进制数据 mp4_data = mp4_data.content # 切割视频的url,将末尾数字作为视频名称并将视频下载保存下来 mp4_name = mp4_str.split('/')[-1] f = open('1.mp4', 'wb') f.write(mp4_data) f.flush()