当前位置:网站首页>爬百度图片
爬百度图片
2022-08-08 16:54:00 【泉伟】
# -*- coding: utf-8 -*-
"""根据搜索词下载百度图片"""
import re
import sys
import urllib
import os
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):
"""给出图片链接列表, 下载所有图片"""
save_path = './DataSet/' + keyword
if not os.path.exists(save_path):
print("Selected folder not exist, try to create it.")
os.makedirs(save_path)
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=5)
string = save_path + '/' + 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('第%d页' % fanye_count)
if fanye_url == '' and onepage_urls == []:
break
all_pic_urls.extend(onepage_urls)
down_pic(list(set(all_pic_urls)))
如果需要下载百度图片时,仅仅是需要主程序第一行关键词修改为自己需要的关键词即可。
如果想详细了解爬虫需要的库以及详细过程可以参考的链接:python——爬虫示例读取豆瓣电影数据
边栏推荐
猜你喜欢
随机推荐
phar反序列化
L2-022 重排链表 (25 分)(模拟链表)
【8.7】代码源 - 【抽卡】【LCM与GCD】
Taro小程序跨端开发入门实战
9. cuBLAS Development Guide Chinese Version--Configuration of Atomic Mode in cuBLAS
bzoj1097 [POI2007]旅游景点atr
ERROR Failed to compile with 1 error
MySQL 表的增删查改
Acwing第 63 场周赛【未完结】
中金财富开户安全吗?怎么操作?
淘宝API常用接口列表与申请方式
六、Jmeter定时器
通俗易懂的epoll
L2-021 点赞狂魔 (25 分)
L2-010 排座位 (25 分) (DFS)
英特尔两大 FPGA 产品已部署至中国创新中心:性能提高 45%,功耗降低 40%
PNAS最新研究:81%解题率,神经网络 Codex 推开高等数学世界大门
mysql 索引和 pgsql 索引 命名区别
用完华为云会议解决方案,我直接卸载了之前的会议软件【华为云至简致远】
Web3构架是怎么样的?