首页 > 其他分享 >普象搜索词图片爬取

普象搜索词图片爬取

时间:2023-10-09 16:22:57浏览次数:33  
标签:term img 普象 搜索词 search detail 爬取 path folder

功能说明:

  1. 搜索普象网站以获取与特定搜索词相关的图片。
  2. 将找到的每张图片保存到用户指定的文件夹中。
  3. 允许并发下载,加速下载过程。

目的: 该代码主要是为了方便用户从普象网站批量下载与搜索词相关的图片。

使用注意事项:

  1. 在使用此脚本时,确保已安装所有必要的Python库,例如:os, requests, BeautifulSoupThreadPoolExecutor
  2. 使用时应确保有足够的磁盘空间来保存下载的图片。
  3. 由于该脚本使用了多线程下载,可能会对普象网站产生较大的访问压力,请谨慎使用并尽量不要频繁运行。
  4. 普象网站结构或内容可能会发生变化,如果未来网站结构发生变化,该脚本可能需要进行相应的修改。

语法:

  1. download_image(img_url, folder_path): 下载指定URL的图片并保存到指定的文件夹中。
  2. get_images_from_details(detail_url): 从给定的详情URL获取所有的图片URLs。
  3. fetch_and_save_images_for_term(search_term, base_folder_path): 根据指定的搜索词,搜索普象网站并下载找到的所有图片,将其保存到指定的文件夹中。
  4. main(): 脚本的主函数,用于获取用户输入并触发搜索与下载过程。
  5. if __name__ == "__main__":: 确保脚本只在直接运行时执行,而不是在导入时。

import os
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor

BASE_URL = "https://www.puxiang.com"
DETAILS_PREFIX = BASE_URL + "/galleries/"

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}


def download_image(img_url, folder_path):
try:
img_data = requests.get(img_url, headers=headers).content
file_path = os.path.join(folder_path, img_url.split('/')[-1])
with open(file_path, 'wb') as handler:
handler.write(img_data)
print(f"Downloaded and saved to {file_path}")
except Exception as e:
print(f"Error downloading {img_url}. Error: {e}")


def get_images_from_details(detail_url):
response = requests.get(detail_url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
image_tags = soup.find_all("img")

# Filter the img_urls
img_urls = [img['data-src'] for img in image_tags if
img.get('data-src', '').startswith("https://assets.puxiang.com")]
return img_urls


def fetch_and_save_images_for_term(search_term, base_folder_path):
page_num = 1
while True:
SEARCH_URL = BASE_URL + f"/search/puxiang?page={page_num}&key=" + requests.utils.quote(search_term)

response = requests.get(SEARCH_URL, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

# Create a folder for this search term if not exist
folder_name = "普象--" + search_term
folder_path = os.path.join(base_folder_path, folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)

# Get details links
detail_links = [BASE_URL + a['href'] for a in soup.find_all("a", class_="work-img")]

# If no detail links are found on this page, break the loop
if not detail_links:
break

# Use ThreadPoolExecutor for concurrent downloading
with ThreadPoolExecutor(max_workers=4) as executor:
for detail_link in detail_links:
img_urls = get_images_from_details(detail_link)
for img_url in img_urls:
executor.submit(download_image, img_url, folder_path)
print(f"Queued images from {detail_link} for search term '{search_term}' on page {page_num}")

# Move to the next page
page_num += 1


def main():
# Ask for the base folder path
base_folder_path = input("请输入保存的文件夹位置,例如:C:\\Users\\皮皮\\Desktop\\花瓣牛马下载: ")

# Ask for search terms
search_terms = input("请输入搜索词,多个搜索词用逗号分隔,例如:爆炸,c4d: ").split(',')

for term in search_terms:
fetch_and_save_images_for_term(term.strip(), base_folder_path)

print("Done!")


if __name__ == "__main__":
main()

 

标签:term,img,普象,搜索词,search,detail,爬取,path,folder
From: https://www.cnblogs.com/zly324/p/17752037.html

相关文章

  • 由于蚂蚁老师课程视频中博客园网站更新,代码不适用于现有环境,故网上查找更新:网上爬取博
    importjsonimportreimportrequestsfrombs4importBeautifulSoupfOut=open("博客爬取文章列表标题及地址.txt","w",encoding="utf8")foridxinrange(20):print("#"*50,idx+1)url="https://www.cnblogs.com/AggSite/......
  • 自动化爬取Behance网站上的项目链接(优化版)
    ###代码功能:此代码的主要目的是自动化爬取Behance网站上的项目链接。1.**多关键词搜索**:用户可以一次性输入多个关键词,程序会为每个关键词爬取指定数量的项目链接。2.**自动滚动页面**:使用Selenium模拟浏览器操作,程序能自动地滚动页面以获取更多的链接。3.**命令行界面......
  • 爬取behance搜索结果图片背后详情页的链接
    目的:我需要搜索多个behance结果,如“washingmachine","refrigerator"等,把结果下详情页高清大图都下载到本地。这样我就获得了“冰箱”的大量高清图。程序作用:爬取多个搜索结果下的详情页链接,并新建文件后保存在桌面txt文件中,如“washingmachine.txt”中。后期把txt中的文本可以放......
  • 批量爬取多分页多张图片
    importurllib.requestfromlxmlimportetree#https://sc.chinaz.com/tupian/siwameinvtupian.htmlurl='https://sc.chinaz.com/tupian/siwameinvtupian_2.html'defgetTenGirlPhote(page):headers={'User-Agent':'Mozil......
  • 爬取豆瓣电影,保存到json文件中
    importurllib.requesturl='https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=0&limit=20'headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537......
  • 爬虫记录~(多线程爬取图片)
    使用Requests+Re库方法多线程爬取亚马逊商城商品图片,以关键词“书包”搜索页面的商品的图片,爬取0-2页面商品图片。关键词:多线程爬虫程序、商城网站的遍历,链接的查找和访问。巩固搜索接口和翻页处理。importrequestsfromfake_useragentimportUserAgentimportrefrommulti......
  • python爬取手机壁纸
    无聊随便玩玩,要爬成功还早着呢,代码很乱可以整理,写了就记录一下吧,有机会再改。importrequestsimportosfrombs4importBeautifulSoupfromrequests.packagesimporturllib3importrandomimportthreadingimporttimeurllib3.disable_warnings()start_page=1end_......
  • Python爬虫-爬取百度搜索结果页的网页标题及其真实网址
    共两个依赖的需提前安装的第三方库:requests和bs4库cmd命令行输入安装requests库:pip3install-ihttps://pypi.douban.com/simplerequests安装bs4库:pip3install-ihttps://pypi.douban.com/simplebeautifulsoup4 本微项目源文件下载地址:https://wwuw.lanzouj.com/i1Au51......
  • 这是一个很有趣的爬虫代码,可以爬取指定地区的91论坛帖子,你会得到一个yp信息集锦 So c
    varNightmare=require('nightmare');//https://duckduckgo.comfunctionopen(page){varnightmare=Nightmare({show:false});//console.log(`开始爬取=https://t0904.91zuixindizhi.com/forumdisplay.php?fid=19&page=${page}`);nigh......
  • 【Python爬虫】批量爬取豆瓣电影排行Top250
    ​    今天给大家分享下我刚开始接触Python时学习的爬虫程序,代码部分很简单,不过当时刚开始学习时还是走了不少弯路的。这个爬虫程序应该是很多书里面的入门练手程序,主要就是去豆瓣爬取电影评分排行前250。        本篇文章只做学习交流使用,不涉及任何商业用途......