前言:很多小伙伴估计和我一样刚刚开始学习爬虫时总想要蠢蠢欲动,去爬取一些网页的素材,今天我将要和大家分享一个用python脚本自搜索爬取百度图片(这里只是以学习为目的,不涉及其它相关违反百度利益的操作)
工具:编辑器,python环境。
用途:很多时候学习是不抱着目的性去的,大部分人也许只是对爬虫感兴趣,就要去学它。本人之前也是抱着这样的想法,但是却在今后的比赛中运用到了它,在英伟达举办的一些人工智能学习方面的比赛中就需要运用爬虫去爬取大量的图片素材做成数据集,当然还有其它方面的诸多应用…
自搜索栏:
爬取的图片自动存储:
代码展示:
# -*- coding: utf-8 -*-
# @Date : 2020-07-29 17.51
# @Author : Ete
# @obiect :Pictures_Crawling from baidu
import requests
import re
def client():
global search_words
global pages
global pages_1
search_words = input('搜索栏:')
pages = input('爬取页数:')
pages_1 = int(pages)
#图片爬取函数
def Pictures_Crawling():
for page in range(1,pages_1):
url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={}&pn={}'.format(search_words, page)
#url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1600582955784_R&pv=&ic=0&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=%E9%81%93%E8%B7%AF%E7%A6%81%E6%AD%A2%E8%B7%AF%E6%A0%87'
#伪装浏览器请求头
headers={
'user-agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 84.0 .4147.89Safari / 537.36'
}
#获取网站源码
html = requests.get(url,headers=headers)
#获取真实的url
urls_real = re.findall('"thumbURL":"(.*?)",', html.text)
#print(urls_real)
#筛选资源url,并返回元组
#urls = re.findall(r'<img alt="" src="(http://.*?.jpg)" ',html.text)
#资源存放文件夹路径
root = 'E:\\Python files\\images_mandatory\\'
#print(urls)
for i in urls_real :
path = root + i.split('/')[-1] #资源存放点+资源存放名称
print(path)
image_data = requests.get(i,headers=headers)
with open(path, 'wb')as f: #将图片以二进制写入
f.write(image_data.content)
#主函数
if __name__ == '__main__':
client()
Pictures_Crawling()