一:用selenium-wire和requests實現(xiàn)單張百度圖片下載
百度首頁.png
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from seleniumwire.webdriver import Chrome
import requests
driver = Chrome(options= Options())
driver.get("https://www.baidu.com/")
driver.maximize_window()
time.sleep(3)
#右鍵點擊圖片乳蓄,在新的頁面打開咪橙,可以在地址欄查看到圖片地址和圖片名稱,當(dāng)前圖片名稱為:PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png
#利用selenium-wire的功能虚倒,將接口返回的內(nèi)容放進itemlist中美侦,遍歷url,查找接口中包含圖片名稱url(如找不到魂奥,則報錯)菠剩,
results = [item for item in driver.requests
if 'PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png' in item.url]
if len(results) == 0:
raise Exception('沒有找到百度圖片!')
#將找到的圖片保存耻煤,默認保存在程序運行的文件夾中
with open('baidu.png', 'wb') as f:
f.write(results[0].response.body)
二:用selenium-wire和requests下載天貓商城圖片列表中的全部圖片
下載天貓商城圖片列表中的全部圖片.png
用‘/’分割圖片url具壮,截圖最后一段作為圖片名稱.png
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from seleniumwire.webdriver import Chrome
import requests
driver = Chrome(options= Options())
driver.get("https://www.tmall.com/")
driver.maximize_window()
time.sleep(3)
#獲取圖片list准颓,圖片塊,圖片img
imgModule = driver.find_element(By.XPATH,"http://div[@class ='rax-view-v2 FloorModule--tmcsModule--27mV5Wq']")
imgContentItems = imgModule.find_elements(By.XPATH,"./div[2]/div")
# 滾動條滑動至圖片列表最后一張圖片處
driver.execute_script('arguments[0].scrollIntoView(false);', imgContentItems[-1])
#遍歷獲取所有圖片
for img in imgContentItems:
#拿到圖片的url
img_url_ele = (img.find_element(By.XPATH, "./a/img"))
img_url = img_url_ele.get_attribute('src')
split_list = img_url.split('/')
# 用‘/’分割圖片url棺妓,截圖最后一段作為圖片名稱
img_name = split_list[-1]
r=requests.get(img_url)
#下載圖片
with open(img_name, 'wb') as f:
f.write(r.content)
driver.close()
成功下載圖片.png