厚积薄发爱python 2019-10-27 15:22:53
本代码演示通过python的requests,BeautifulSoup库批量下载360图片,并保存在本机的路径
代码如下:
#BeautifulSoup库是网页爬虫解析库,主要用来对HTML源代码进行解析,方便显示并读取相应的标签数据
#1、首先导入相应的库
import requests
from bs4 import BeautifulSoup
import random
import os
import time
#2、对网站进行get请求
def gethtml(kward):
try:
url="https://image.so.com" #设置360网站的搜索页面的前面部分网址
kw={"q":kward} #设置关键字变量kw
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"} # 设置网页请求头
response = requests.get(url, params=kw,headers=headers) ##伪装浏览器对url进行get请求,传递的参数是kw
response.encoding=response.apparent_encoding #根据网页内容解析出编码格式并赋值给response.encoding
html=response.text #将网页源代码赋值给html
soup=BeautifulSoup(html,'html.parser') #使用html.parser对html代码进行解析,并赋值给soup变量
print(soup.head) #打印网页源代码的头部信息
images=soup.find_all('img') #查找源代码里所有的图片标签
path="F://明星照片//"+kward+"//" #设置图片的存储本机的路径
for img in images: #遍历所有的img标签信息
print(img.attrs["src"]) #打印遍历出来的图片表情的src属性值
url1=img.attrs["src"] #设置url1为遍历出来的图片表情的src属性值
response1=requests.get(url=url1,headers=headers)
#上行代码伪装浏览器对url1,即图片网站进行get请求并将请求结果赋值给response1
response1.encoding=response1.apparent_encoding #根据网页内容解析出编码格式并赋值给response1.encoding
html1=response1.content #将图片网址的二进制源代码赋值给html1
abspath=path+str(random.random())+".jpg" #设置存储路劲为abspath
with open(abspath,"wb") as f: #打开文件的绝对路径,并对文件进行写入操作,并设置为f
f.write(html1) #将源代码写入f文件
f.close() #关闭f文件
print(img.attrs["src"]+"下载成功") #打印下载成功的提示
time.sleep(0.2) #设置时间休眠0.2秒
except: #如果接受错误时
print("爬取失败") #打印爬取失败
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4822/viewspace-3153361/ ,如需转载,请注明出处,否则将追究法律责任。