python 爬图片代码
Python是一种简单易学的编程语言,也是一种功能强大的网络爬虫工具。本文将介绍怎样使用Python爬取网页中的图片,并且将代码放在pre标签中。
# 导入所需的库 import requests from bs4 import BeautifulSoup import os # 获得网页HTML代码 url = 'https://www.google.com/search?q=cute+cats&tbm=isch' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} res = requests.get(url, headers=headers) htmlContent = res.text # 使用BeautifulSoup解析HTML代码 soup = BeautifulSoup(htmlContent, "html.parser") imgLinks = soup.find_all('img') # 创建一个文件夹以存储图片 if not os.path.exists('cute_cats'): os.makedirs('cute_cats') # 遍历所有图片链接并下载 for i, link in enumerate(imgLinks): imgUrl = link.get('src') if imgUrl: imgData = requests.get(imgUrl).content with open('cute_cats/%d.jpg' % i, 'wb') as handler: handler.write(imgData) print('成功下载图片%d' % i)
本文的Python代码使用requests库从网上获得HTML代码,然后使用BeautifulSoup库解析HTML代码以寻觅图片链接。最后,我们使用requests库下载所有的图片,并将它们保存在一个新文件夹中。这样就可以轻松地将图片爬取到本地电脑中。
文章来源:丸子建站
文章标题:python 爬图片代码
https://www.wanzijz.com/view/74547.html