突發奇想,給各位爬爬壁紙圖片,話不多說,開始行動,如果文章對你有幫助,點贊,收藏,
一,知道爬取自己想要的壁紙圖片網址
模型寫出來
'''
爬取網路圖片
1,要到主頁面的原始碼,從主頁面拿到子頁面連接
2,通過子頁面內容,找到子頁面下載路徑
3,下載圖片
'''
def picture():
host_page(url)
son_page()
download()
def host_page():
#獲取主頁面
pass
def son_page():
#獲取子頁面
pass
def download():
#下載圖片
pass
if __name__ == '__main__':
picture()
目標

點擊f12,進入開發者模式,找到自己需要的圖片(或者點擊滑鼠右鍵,點擊檢查也可以)

'''
爬取網路圖片
1,要到主頁面的原始碼,從主頁面拿到子頁面連接
2,通過子頁面內容,找到子頁面下載路徑
3,下載圖片
'''
import requests
from bs4 import BeautifulSoup
import time
def picture():
host_page()
download()
def host_page():
#獲取主頁面
url='https://pic.netbian.com/4kfengjing/'
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47"
} # 模擬的服務器頭
resp=requests.get(url,headers=headers)#換頭
newurl=BeautifulSoup(resp.text,'html.parser')#主頁面內容就出來了
print(newurl)
def download():
#下載圖片
pass
if __name__ == '__main__':
host_page()
顯示亂碼,所以進行編碼更改
參考操作地址:https://editor.csdn.net/md/?articleId=112390388(處理方法小撰寫弄一個單獨的博客,歡迎大家觀看)


處理完亂碼,進行篩選,選擇自己想要內容,
'''
爬取網路圖片
1,要到主頁面的原始碼,從主頁面拿到子頁面連接
2,通過子頁面內容,找到子頁面下載路徑
3,下載圖片
'''
import requests
from bs4 import BeautifulSoup
import time
def picture():
host_page()
download()
def host_page():
#獲取主頁面
url='https://pic.netbian.com/4kfengjing/'
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47"
} # 模擬的服務器頭
resp=requests.get(url,headers=headers)#換頭
resp.encoding='gbk'#處理亂碼
newurl=BeautifulSoup(resp.text,'html.parser')#主頁面內容就出來了
alist=newurl.find('div',class_='slist').find_all("a")#查找a標簽
for i in alist :
print(i.get('href'))#獲取子頁面
def download():
#下載圖片
pass
if __name__ == '__main__':
host_page()
現象:地址
下面創建一個檔案夾,用來存盤照片,

'''
爬取網路圖片
1,要到主頁面的原始碼,從主頁面拿到子頁面連接
2,通過子頁面內容,找到子頁面下載路徑
3,下載圖片
'''
import requests
from bs4 import BeautifulSoup
import time
def picture():
#獲取主頁面
url='https://pic.netbian.com/4kfengjing/'
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47"
} # 模擬的服務器頭
resp=requests.get(url,headers=headers)#換頭
resp.encoding='gbk'#處理亂碼
newurl=BeautifulSoup(resp.text,'html.parser')#主頁面內容就出來了
alist=newurl.find('div',class_='slist').find_all("a")#查找a標簽
for i in alist :
href=i.get('href')#獲取子頁面
child_resp=requests.get('https://pic.netbian.com/'+href)
child_resp.encoding='gbk'
text=child_resp.text
child_page = BeautifulSoup(text, 'html.parser')
a=child_page.find('a',id='img')
img=a.find('img')
src=img.get('src')
#下載圖片
print(src)
img_resp=requests.get('https://pic.netbian.com/tupian/21953.html'+src)
img_name=src.split("/")[-1]#取url中最后一個/以后內容為名字
with open('picture/'+img_name,mode='wb') as f :
f.write(img_resp.content) #圖片內容獲取
print('下載完成')
time.sleep(1)#防止ip地址被封,休息1秒后繼續
if __name__ == '__main__':
picture()


檔案夾取消索引(方便)

好了,就完成了,謝謝大家觀看,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/267130.html
標籤:python
