Python 爬取百度图片 - 代码示例和教程
以下是一个使用Python爬取百度图片的程序示例:
import requests
import os
def download_images(keyword, num_images):
url = 'https://image.baidu.com/search/acjson'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'
}
params = {
'tn': 'resultjson_com',
'logid': 'xxxxxxxxxx', # 使用自己的logid
'ipn': 'rj',
'ct': 201326592,
'is': '',
'fp': 'result',
'queryWord': keyword,
'cl': 2,
'lm': -1,
'ie': 'utf-8',
'oe': 'utf-8',
'adpicid': '',
'st': -1,
'z': '',
'ic': '',
'hd': '',
'latest': '',
'word': keyword,
's': '',
'se': '',
'tab': '',
'width': '',
'height': '',
'face': '',
'istype': '',
'qc': '',
'nc': '',
'fr': '',
'expermode': '',
'force': '',
'pn': 0,
'rn': 30 * num_images,
'gsm': '1e',
'1568113288100': ''
}
response = requests.get(url, headers=headers, params=params)
json_data = response.json()
save_dir = './images/' + keyword + '/'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for i, data in enumerate(json_data['data']):
if 'thumbURL' in data:
image_url = data['thumbURL']
response = requests.get(image_url, headers=headers)
with open(save_dir + str(i+1) + '.jpg', 'wb') as f:
f.write(response.content)
print('Successfully downloaded', str(i+1), 'image(s)')
print('All images downloaded successfully!')
keyword = input('Enter the keyword: ')
num_images = int(input('Enter the number of images to download: '))
download_images(keyword, num_images)
在这个示例中,我们使用了requests库来发送HTTP请求,并使用json库来解析返回的JSON数据。程序会根据给定的关键字和要下载的图片数量,通过发送HTTP请求获取百度图片搜索结果的JSON数据,并提取其中的图片URL。然后,程序会将这些图片下载到指定的文件夹中。
请注意,在使用此程序之前,您需要安装requests库,并将程序中的xxxxxxxxxx替换为您自己的logid。另外,您还需要创建一个名为images的文件夹来保存下载的图片。
希望这个例子对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/pD9d 著作权归作者所有。请勿转载和采集!