下面是一个使用 Python 编写的爬虫脚本,可以按照给定的关键词爬取https://www.pexels.com/zh-cn/search/网站上的图片。\n\npython\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\n\ndef download_image(url, folder_path):\n response = requests.get(url)\n if response.status_code == 200:\n file_name = url.split("/")[-1]\n file_path = os.path.join(folder_path, file_name)\n with open(file_path, "wb") as file:\n file.write(response.content)\n print("Downloaded:", file_name)\n else:\n print("Failed to download:", url)\n\ndef crawl_images(keyword):\n base_url = f"https://www.pexels.com/zh-cn/search/{keyword}/"\n response = requests.get(base_url)\n if response.status_code == 200:\n soup = BeautifulSoup(response.content, "html.parser")\n images = soup.find_all("img", class_="photo-item__img")\n folder_path = os.path.join(os.getcwd(), keyword)\n os.makedirs(folder_path, exist_ok=True)\n for img in images:\n image_url = img["src"]\n download_image(image_url, folder_path)\n else:\n print("Failed to connect to the website.")\n\n# 按关键词爬取图片\ncrawl_images("自拍")\n\n\n请确保在运行之前已安装requestsbeautifulsoup4库。你可以使用以下命令安装它们:\n\n\npip install requests beautifulsoup4\n\n\n运行脚本后,它将在当前工作目录中创建一个名为"自拍"的文件夹,并将所有下载的图片保存在该文件夹中。

Python 爬虫脚本:从 Pexels 网站抓取图片

原文地址: https://www.cveoy.top/t/topic/qE90 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录