剛學習爬蟲,寫了一個百度圖片爬蟲看成練習。html
環境:python3.6(請下好第三方庫requests)python
實現的功能:輸入關鍵字,下載240張關鍵字有關的百度圖片到本地的d:\百度圖片\關鍵字\文件夾中。ajax
百度圖片的加載是ajax異步形式的,除了前面的一部分圖片,後面靠下拉加載的圖片都是異步從服務器端請求獲得的。這些異步加載的圖片的信息能夠在一個個acjson的百度圖片接口中,能夠在開發者工具中xhr下找到這些文件。json
接下來上代碼:服務器
import requestsimport reimport osdef get_page_url(url, param): response = requests.get(url, params=param) response.encoding = 'utf-8' return response.textdef parse_page(str): pattern = re.compile('"middleURL":"(.*?)",')#利用正則匹配圖片url url_list = re.findall(pattern, str) return url_listdef 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') continuedef 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 pathdef main(): keyword = input("input keyword about images you want to download: ") path = make_dir(keyword) run(keyword, path)if __name__ == '__main__': main()