1. 程式人生 > >百度圖片小爬蟲

百度圖片小爬蟲

body compile pan .text 輸入關鍵字 存在 down download spa

剛學習爬蟲,寫了一個百度圖片爬蟲當作練習。

環境:python3.6(請下好第三方庫requests)

實現的功能:輸入關鍵字,下載240張關鍵字有關的百度圖片到本地的d:\百度圖片\關鍵字\文件夾中。

百度圖片的加載是ajax異步形式的,除了前面的一部分圖片,後面靠下拉加載的圖片都是異步從服務器端請求得到的。這些異步加載的圖片的信息可以在一個個acjson的百度圖片接口中,可以在開發者工具中xhr下找到這些文件。

接下來上代碼:

import requests
import re
import os


def get_page_url(url, param):
response = requests.get(url, params=param)
response.encoding = ‘utf-8‘
return response.text


def parse_page(str):
pattern = re.compile(‘"middleURL":"(.*?)",‘)#利用正則匹配圖片url
url_list = re.findall(pattern, str)
return url_list


def run(keyword, path):
url = "https://image.baidu.com/search/acjson"
i = 0
for j in range(30, 270, 30):
params = {"ipn": "rj", "tn": "resultjson_com", "word": keyword, "pn": str(j)}
html = get_page_url(url, params)
lists = parse_page(html)
print(lists)
for item in lists:
try:
img_data = requests.get(item, timeout=10).content
with open(path + "/" + str(i) + ".jpg", "wb") as f:
f.write(img_data)
f.close()
i = i+1
except requests.exceptions.ConnectionError:
print(‘can not download‘)
continue


def make_dir(keyword):
path = "D:/百度圖片/"
path = path+keyword
is_exists = os.path.exists(path)
if not is_exists:
os.makedirs(path)
return path
else:
print(path + ‘目錄已存在‘)
return path


def main():
keyword = input("input keyword about images you want to download: ")
path = make_dir(keyword)
run(keyword, path)


if __name__ == ‘__main__‘:
main()

百度圖片小爬蟲