Python爬虫 爬取百度图片(使用selenium库web driver实现)
闲着没事想写一个爬虫去爬取一下百度图片,但是通过连接访问发现返回的是 百度安全验证,然后发现selenium下的web driver可以直接调起浏览器访问网址,并且可以拿到网站内容,所以根据这个写了一个爬虫,代码可以在window上直接运行。
所需第三方库
import time #用于调起浏览器 from selenium import webdriver # 用来解析网页内容 from bs4 import BeautifulSoup import os, requests,re
安装第三方库
可以考虑使用阿里云镜像加快安装速度,只需要把bs4换成对应的第三方库就可以。
pip install -i https://mirrors.aliyun.com/pypi/simple/ bs4
观察页面代码,查看自己需要爬去的标签格式
通过F12查看页面源代码可以发现,图片的标签是 index:
titleIndex = getImageTitle(title, titleIndex)
imageName = "".join(re.findall(pattern, title[titleIndex].text))
if imageName == "":
imageName = "default" + str(index)
titleIndex += 1
imageName += ".jpg"
print("准备下载第%s个图片,名字叫:%s 地址:%s" % (str(index+1), imageName, imageUrl))
savePhoto(imageUrl, imageName)
# 页面里有很多class=imgitem-title的标签,图片的标题一般有title属性,根据title属性过滤标签
def getImageTitle(title, index):
if "title" in title[index].attrs:
return index
else:
getImageTitle(title, index + 1)
return index + 1
# 保存照片
def savePhoto(imageUrl, filename):
p = os.path.join(path, filename)
c = requests.get(imageUrl)
createFile(path)
with open(p, 'wb') as f:
f.write(c.content)
time.sleep(0.3)
print("下载完了 休息0.3秒")
# 创建本地文件
def createFile(path):
print("path:",path)
file = os.path.exists(path)
if not file:
os.makedirs(path)
# 滑动浏览器窗口,加载更多图片,滑动一次加载20多张图片
# numer为想滑动的次数
def slideBrowseWindow(driver, number):
for i in range(number):
time.sleep(0.1)
driver.execute_script("window.scrollBy(0,{})".format(i * 1000))
time.sleep(0.3)
if __name__ == "__main__":
#这里的豪车可以改成自己想搜索的内容
searchName = "豪车"
#这里使用的是edge浏览器,如果想使用谷歌浏览器,可以换成webdriver.Chrome()
driver = webdriver.Edge()
driver.get("https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1709260324755_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&dyTabStr=MCwxLDMsMiw4LDYsNCw1LDcsOQ%3D%3D&ie=utf-8&sid=&word="+ searchName +"&f=3&oq=%E7%BE%8E%E5%A5%B3&rsp=0")
# 百度图片是下滑加载更多
slideBrowseWindow(driver, 10)
# 获取页面的源代码
page_source = driver.page_source
# 输出页面源代码
parseHtml(page_source)
driver.quit()
print("done.")
还没有评论,来说两句吧...