目錄
一:爬蟲基礎(chǔ)
二:安裝html解析的python工具
三:爬取網(wǎng)頁圖片
一:爬蟲基礎(chǔ)
爬蟲基本過程:
1.請(qǐng)求標(biāo)頭 headers
2.創(chuàng)建一個(gè)會(huì)話 requests.Session
3.確定請(qǐng)求的路徑
4.根據(jù)路徑獲取網(wǎng)頁資源(HTML文件)
5.解析html文件BeautifulSoup div a 標(biāo)簽 獲取對(duì)應(yīng)的圖片
6.建立網(wǎng)絡(luò)連接進(jìn)行下載? 創(chuàng)建出下載的圖片
了解基本HTML結(jié)構(gòu)
保存帶有圖片的網(wǎng)頁
查找?guī)в衐ata-imgurl屬性的標(biāo)簽獲取url
<html>
<head></head>
<body></body>
</html>
頭:引用資源
體:包含一切標(biāo)簽
可以 F12 或者 ctrl+shift+i 打開控制臺(tái),查看網(wǎng)頁代碼,獲取自己想要的信息
二:安裝html解析的python工具
具體可以參考下面的這篇文章:
https://blog.csdn.net/m0_56051805/article/details/128407402
三:爬取網(wǎng)頁圖片
以爬取百度網(wǎng)頁圖片為例,大致實(shí)現(xiàn)如下
根據(jù)地址查找對(duì)應(yīng)圖片的信息:
# 根據(jù)地址去查找 對(duì)應(yīng)的圖片的信息
def Find(url, A):
global List # 保存信息的列表
print('正在檢測(cè)圖片總數(shù),請(qǐng)稍等.....')
t = 0
i = 1
s = 0
while t < 1000:
# 時(shí)間戳 不簡(jiǎn)單刷新訪問網(wǎng)址
Url = url + str(t)
try:
# get獲取數(shù)據(jù)
Result = A.get(Url, timeout=7, allow_redirects=False)
except BaseException:
t = t + 60
continue
else:
# 拿到網(wǎng)站的數(shù)據(jù)
result = Result.text
# 找到圖片url
pic_url = re.findall('"objURL":"(.*?)",', result, re.S)
# 圖片總數(shù)
s += len(pic_url)
if len(pic_url) == 0:
break
else:
List.append(pic_url)
t = t + 60
return s
記錄下相關(guān)的數(shù)據(jù)信息:
# 記錄相關(guān)數(shù)據(jù)
def recommend(url):
Re = []
try:
html = requests.get(url, allow_redirects=False)
except error.HTTPError as e:
return
else:
html.encoding = 'utf-8'
# html文件解析
bsObj = BeautifulSoup(html.text, 'html.parser')
div = bsObj.find('div', id='topRS')
if div is not None:
listA = div.findAll('a')
for i in listA:
if i is not None:
Re.append(i.get_text())
return Re
對(duì)相應(yīng)網(wǎng)頁的圖片進(jìn)行下載:
# 下載圖片
def dowmloadPicture(html, keyword):
global num
# 找到圖片url
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
print('找到關(guān)鍵詞:' + keyword + '的圖片,開始下載圖片....')
for each in pic_url:
print('正在下載第' + str(num + 1) + '張圖片,圖片地址:' + str(each))
try:
if each is not None:
pic = requests.get(each, timeout=7)
else:
continue
except BaseException:
print('錯(cuò)誤,當(dāng)前圖片無法下載')
continue
else:
string = file + r'\\' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
return
偽裝成瀏覽器向網(wǎng)頁提取服務(wù):
if __name__ == '__main__': # 主函數(shù)入口
# 模擬瀏覽器 請(qǐng)求數(shù)據(jù) 偽裝成瀏覽器向網(wǎng)頁提取服務(wù)
headers = {
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
'Upgrade-Insecure-Requests': '1'
}
# 創(chuàng)建一個(gè)請(qǐng)求的會(huì)話
A = requests.Session()
# 設(shè)置頭部信息
A.headers = headers
word = input("輸入要搜索的關(guān)鍵詞:")
# 拼接路徑
url = 'https://image.baidu.com/search/flip?ct=201326592&cl=2&st=-1&lm=-1&nc=1&ie=utf-8&tn=baiduimage&ipn=r&rps=1&pv=&fm=rs1&word=' + word
# 根據(jù)路徑去查找
total = Find(url, A)
# 記錄相關(guān)推薦圖片
Recommend = recommend(url)
print('經(jīng)過檢測(cè)%s類圖片共有%d張' % (word, total))
numPicture = int(input('輸入要下載的數(shù)量'))
file = input('請(qǐng)建立一個(gè)存儲(chǔ)圖片的文件夾,輸入文件夾名稱即可: ')
y = os.path.exists(file)
if y == 1:
print('該文件已存在,請(qǐng)重新輸入')
file = input('請(qǐng)建立一個(gè)存儲(chǔ)圖片的文件夾,)輸入文件夾名稱即可: ')
os.mkdir(file)
else:
os.mkdir(file)
t = 0
tmp = url
while t < numPicture:
try:
url = tmp + str(t)
result = requests.get(url, timeout=10)
print(url)
except error.HTTPError as e:
print('網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)調(diào)整網(wǎng)絡(luò)后重試')
t = t + 60
else:
dowmloadPicture(result.text, word)
t = t + 60
測(cè)試過程如下
1 輸入要搜索的圖片,可以檢索網(wǎng)頁圖片的數(shù)量
2 輸入自己想要下載的圖片數(shù)量,同時(shí)創(chuàng)建一個(gè)存儲(chǔ)下載圖片的文件夾
3 等待下載完即可
4 到新創(chuàng)建的文件夾下可以查看到,網(wǎng)頁上獲取到的圖片已經(jīng)下載
文章學(xué)習(xí)自:?學(xué)術(shù)菜鳥小晨 博主的文章
百度,搜狗,360網(wǎng)絡(luò)爬圖文章來源:http://www.zghlxwxcb.cn/news/detail-781493.html
完整源碼分享如下文章來源地址http://www.zghlxwxcb.cn/news/detail-781493.html
import re
import requests
from urllib import error
from bs4 import BeautifulSoup
import os
num = 0
numPicture = 0
file = ''
List = []
# 根據(jù)地址去查找 對(duì)應(yīng)的圖片的信息
def Find(url, A):
global List # 保存信息的列表
print('正在檢測(cè)圖片總數(shù),請(qǐng)稍等.....')
t = 0
i = 1
s = 0
while t < 1000:
# 時(shí)間戳 不簡(jiǎn)單刷新訪問網(wǎng)址
Url = url + str(t)
try:
# get獲取數(shù)據(jù)
Result = A.get(Url, timeout=7, allow_redirects=False)
except BaseException:
t = t + 60
continue
else:
# 拿到網(wǎng)站的數(shù)據(jù)
result = Result.text
# 找到圖片url
pic_url = re.findall('"objURL":"(.*?)",', result, re.S)
# 圖片總數(shù)
s += len(pic_url)
if len(pic_url) == 0:
break
else:
List.append(pic_url)
t = t + 60
return s
# 記錄相關(guān)數(shù)據(jù)
def recommend(url):
Re = []
try:
html = requests.get(url, allow_redirects=False)
except error.HTTPError as e:
return
else:
html.encoding = 'utf-8'
# html文件解析
bsObj = BeautifulSoup(html.text, 'html.parser')
div = bsObj.find('div', id='topRS')
if div is not None:
listA = div.findAll('a')
for i in listA:
if i is not None:
Re.append(i.get_text())
return Re
# 下載圖片
def dowmloadPicture(html, keyword):
global num
# 找到圖片url
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
print('找到關(guān)鍵詞:' + keyword + '的圖片,開始下載圖片....')
for each in pic_url:
print('正在下載第' + str(num + 1) + '張圖片,圖片地址:' + str(each))
try:
if each is not None:
pic = requests.get(each, timeout=7)
else:
continue
except BaseException:
print('錯(cuò)誤,當(dāng)前圖片無法下載')
continue
else:
string = file + r'\\' + str(num) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
num += 1
if num >= numPicture:
return
if __name__ == '__main__': # 主函數(shù)入口
# 模擬瀏覽器 請(qǐng)求數(shù)據(jù) 偽裝成瀏覽器向網(wǎng)頁提取服務(wù)
headers = {
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0',
'Upgrade-Insecure-Requests': '1'
}
# 創(chuàng)建一個(gè)請(qǐng)求的會(huì)話
A = requests.Session()
# 設(shè)置頭部信息
A.headers = headers
word = input("輸入要搜索的關(guān)鍵詞:")
# 拼接路徑
url = 'https://image.baidu.com/search/flip?ct=201326592&cl=2&st=-1&lm=-1&nc=1&ie=utf-8&tn=baiduimage&ipn=r&rps=1&pv=&fm=rs1&word=' + word
# 根據(jù)路徑去查找
total = Find(url, A)
# 記錄相關(guān)推薦圖片
Recommend = recommend(url)
print('經(jīng)過檢測(cè)%s類圖片共有%d張' % (word, total))
numPicture = int(input('輸入要下載的數(shù)量'))
file = input('請(qǐng)建立一個(gè)存儲(chǔ)圖片的文件夾,輸入文件夾名稱即可: ')
y = os.path.exists(file)
if y == 1:
print('該文件已存在,請(qǐng)重新輸入')
file = input('請(qǐng)建立一個(gè)存儲(chǔ)圖片的文件夾,)輸入文件夾名稱即可: ')
os.mkdir(file)
else:
os.mkdir(file)
t = 0
tmp = url
while t < numPicture:
try:
url = tmp + str(t)
result = requests.get(url, timeout=10)
print(url)
except error.HTTPError as e:
print('網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)調(diào)整網(wǎng)絡(luò)后重試')
t = t + 60
else:
dowmloadPicture(result.text, word)
t = t + 60
到了這里,關(guān)于python爬蟲 爬取網(wǎng)頁圖片的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!