用python写一个爬虫,爬取google中关于蛇的照片
    		       		warning:
    		            这篇文章距离上次修改已过446天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简单的Python爬虫示例,使用requests库和BeautifulSoup进行网页爬取,爬取Google图片搜索中关于蛇的照片。
首先,你需要安装必要的库(如果尚未安装的话):
pip install requests
pip install beautifulsoup4然后,你可以使用以下代码来实现爬虫:
import requests
from bs4 import BeautifulSoup
import os
 
# 目标网址的前缀
base_url = "https://www.google.com/search?tbm=isch&q=snake"
 
# 图片保存路径
save_path = 'snake_images/'
if not os.path.exists(save_path):
    os.makedirs(save_path)
 
# 用户代理,以防被识别并禁止爬取
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'}
 
def download_image(image_url, file_path):
    response = requests.get(image_url, headers=headers)
    with open(file_path, 'wb') as f:
        f.write(response.content)
        print(f"Image saved: {file_path}")
 
def get_image_urls(url):
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    image_urls = [img['src'] for img in soup.find_all('img', class_='Q4LuWd')]
    return image_urls
 
def main():
    image_urls = get_image_urls(base_url)
    for i, image_url in enumerate(image_urls):
        file_path = os.path.join(save_path, f"snake_{i}.jpg")
        download_image(image_url, file_path)
 
if __name__ == '__main__':
    main()请注意,这个爬虫依赖于Google图片搜索的HTML结构,该结构可能会随着时间变化而变化,因此可能需要进行适当的调整。此外,过度使用此爬虫可能会触发Google的反爬虫机制,导致被封禁。使用爬虫时请遵守相关法律法规,并尊重网站的robots.txt规则。
评论已关闭