14.爬虫
(写在每篇深度学习文章系列的前面,该系列的文章是我2019年做毕设时的步骤总结,是能实现的,不和其他很多博客一样瞎糊弄人浪费时间。写下这些文章一方面为了方便后来者,一方面也为了自己以后的步骤复现等。
另外,如果我给的那些参考帖子看不了了,可以到我的博客下载区那里去下载对应的压缩文件,我把里面所有的链接网页都截了长图,所以不用担心我给的参考帖子链接失效。
其次,如果我给的参考链接侵犯了该链接博主的权益,烦请告知,必当第一时间删掉。由于本人参考帖子较多,如果侵犯了请原谅,我会删掉。也谢谢各位在路上帮助过我的,谢谢了。
还有就是,如果积分太高了,请告诉我怎么把积分降低,我也不太清楚怎么弄,积分会随着下载次数增加逐渐增加。你知道的话怎么降的话可以留言给我。
emm, 最后的最后,如果你觉得这篇博文有用,请点个赞哩,感谢!~~)
(博客下载区:https://download.youkuaiyun.com/download/lininggggggg/11224814
或者在下载区搜索名字:14.爬虫.zip–深度学习文章14)
正文
代码一:
import requests
import os
def getManyPages(keyword,pages):
params=[]
for i in range(30,30*pages+30,30):
params.append({
'tn': 'resultjson_com',
'ipn': 'rj',
'ct': 201326592,
'is': '',
'fp': 'result',
'queryWord': keyword,
'cl': 2,
'lm': -1,
'ie': 'utf-8',
'oe': 'utf-8',
'adpicid': '',
'st': -1,
'z': '',
'ic': 0,
'word': keyword,
's': '',
'se': '',
'tab': '',
'width': '',
'height': '',
'face': 0,
'istype': 2,
'qc': '',
'nc': 1,
'fr': '',
'pn': i,
'rn': 30,
'gsm': '1e',
'1488942260214': ''
})
url = 'https://image.baidu.com/search/acjson'
urls = []
for i in params:
urls.append(requests.get(url,params=i).json().get('data'))
return urls
def getImg(dataList, localPath):
if not os.path.exists(localPath): # 新建文件夹
os.mkdir(localPath)
x = 0
for list in dataList:
for i in list:
if i.get('thumbURL') != None:
print('正在下载:%s' % i.get('thumbURL'))
ir = requests.get(i.get('thumbURL'))
open(localPath + '%d.jpg' % x, 'wb').write(ir.content)
x += 1
else:
print('图片链接不存在')
if __name__ == '__main__':
# dataList = getManyPages('橙子',10) # 参数1:关键字,参数2:要下载的页数
dataList = getManyPages('橙子', 30) # 参数1:关键字,参数2:要下载的页数
getImg(dataList, 'E:\GraduationProject\Data\web_crawler\photo/') # 参数2:指定保存的路径
代码二:
# -*- coding: utf-8 -*-
"""根据搜索词下载百度图片"""
import re
import sys
import urllib
import requests
def get_onepage_urls(onepageurl):
"""获取单个翻页的所有图片的urls+当前翻页的下一翻页的url"""
if not onepageurl:
print('已到最后一页, 结束')
return [], ''
try:
html = requests.get(onepageurl)
html.encoding = 'utf-8'
html = html.text
except Exception as e:
print(e)
pic_urls = []
fanye_url = ''
return pic_urls, fanye_url
pic_urls = re.findall('"objURL":"(.*?)",', html, re.S)
fanye_urls = re.findall(re.compile(r'<a href="(.*)" class="n">下一页</a>'), html, flags=0)
fanye_url = 'http://image.baidu.com' + fanye_urls[0] if fanye_urls else ''
return pic_urls, fanye_url
def down_pic(pic_urls):
"""给出图片链接列表, 下载所有图片"""
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(string, 'wb') as f:
f.write(pic.content)
print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
if __name__ == '__main__':
keyword = '果树上黄色橘子' # 关键词, 改为你想输入的词即可, 相当于在百度图片里搜索一样
url_init_first = r'http://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1497491098685_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&ctd=1497491098685%5E00_1519X735&word='
url_init = url_init_first + urllib.parse.quote(keyword, safe='/')
all_pic_urls = []
onepage_urls, fanye_url = get_onepage_urls(url_init)
all_pic_urls.extend(onepage_urls)
fanye_count = 0 # 累计翻页数
while 1:
onepage_urls, fanye_url = get_onepage_urls(fanye_url)
fanye_count += 1
# print('第页' % str(fanye_count))
if fanye_url == '' and onepage_urls == []:
break
all_pic_urls.extend(onepage_url
s)
down_pic(list(set(all_pic_urls)))
代码三:
# coding =utf-8
# 爬取桔子一张图片
import urllib.request
import re
def getHtml(url):
page = urllib.request.urlopen(url) # 打开页面
html = page.read() # 获取目标页面的源码
return html
if __name__=="__main__":
html = getHtml("http://www.quanjing.com/category/118291.html")
reg = "http://.+?\\.jpg"
img = re.compile(reg)
html = html.decode('utf-8')
imglist = re.findall(img, html)
print(imglist[0])
urllib.request.urlretrieve(imglist[0], 'D:/1.jpg')
代码四:
#!-*- coding:utf-8 -*-
# FileName : img.py
# Author : 优快云_fzs
# Data : 2018/01/10
import re # 导入正则表达式模块
import requests # python HTTP客户端 编写爬虫和测试服务器经常用到的模块
import random # 随机生成一个数,范围[0,1]
# 定义函数方法
def spiderPic(html, keyword):
print('正在查找 ' + keyword + ' 对应的图片,下载中,请稍后......')
for addr in re.findall('"objURL":"(.*?)"', html, re.S): # 查找URL
print('正在爬取URL地址:' + str(addr)[0:30] + '...') # 爬取的地址长度超过30时,用'...'代替后面的内容
try:
pics = requests.get(addr, timeout=5) # 请求URL时间(最大10秒)
except requests.exceptions.ConnectionError:
print('您当前请求的URL地址出现错误')
continue
fq = open('E:\\GraduationProject\\Data\\web_crawler\\picture\\' + (keyword + '_' + str(random.randrange(0, 10000, 10)) + '.jpg'), 'wb') # 下载图片,并保存和命名
fq.write(pics.content)
fq.close()
# python的主方法
if __name__ == '__main__':
word = input('请输入你要搜索的图片关键字:')
result = requests.get(
# 'https://www.quanjing.com/search.aspx?imageUType=p&q=%E6%A9%99%E5%AD%90#橙子||1|100|1|2||||p||')
'http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=' + word)
# 调用函数
spiderPic(result.text, word)