1. 程式人生 > >python+selenium爬取動漫圖片

python+selenium爬取動漫圖片

#在風之動漫網上下載海賊王,輸入需要下載的章節,將漫畫下載的本地
#實現思路:
# 1 海賊王的漫畫目錄連結是:https://www.fzdm.com/manhua/02/
# 2 第X話的漫畫。連線是https://www.fzdm.com/manhua/02/X/,例如,924話連結是https://www.fzdm.com/manhua/02/924/
# 3 第X話漫畫中,第一頁的連結是:https://www.fzdm.com/manhua/02/924/,第二頁是https://www.fzdm.com/manhua/02/924/index_1.html
# 第三頁是https://www.fzdm.com/manhua/02/924/index_2.html,經嘗試,index_0.html就是第一頁的連結
#利用迭代,可以獲得一到最後一頁的圖片,但是無法準確知道那一頁是最後一頁,利用try..exception..函式,丟擲異常,並結束。
#因為,圖片的連結使用js指令碼載入的,無法直接在靜態網頁中獲得http連結,所以使用selenium定點陣圖片位置,然後使用get_attribute('src')
#獲得圖片的連結
#之後用resquests請求,將圖片下載的本地
#


from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import requests
import time
import os
import sys
def manhua_download():
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars') # 關閉自動化程式執行的提示
# option.add_argument('--headless') #隱藏瀏覽器視窗
driver=webdriver.Chrome(options=option)
#上面三行可以使得瀏覽器不彈出自動化測試的攔截視窗
x=input("請問要下載第幾話?請輸入:")
url=os.path.join('https://manhua.fzdm.com/2/',x)
# 建立章節目錄
dirname = '第' + str(x) + '話'
  #判斷資料夾是否已經存在
if not os.path.exists(dirname):
os.mkdir(dirname)
print('資料夾建立完畢')
  
#因為海賊王的每一話,沒有超過30頁的,所以設定range是30,這樣可以保證每一頁都爬取下來,但是會導致超過最後一頁後,會異常。
for i in range(30):

index='index_'+str(i)+'.html'
final_url=os.path.join(url,index)
driver.get(final_url)
try:
img_path = driver.find_element_by_xpath(".//img[@id='mhpic']")
except NoSuchElementException:
print('下載完畢')
driver.quit()
sys.exit() #捕獲異常後退出程式
img_url = img_path.get_attribute('src') # get_attribute('src') 獲取src內的內容
print(img_url)
time.sleep(0.1)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0'}
response = requests.get(img_url,headers=headers)
image_name=dirname+'/'+str(i+1)+'.jpg' #實現下載的圖片存到指定的資料夾的功能
with open(image_name,'wb') as f:
f.write(response.content)
print('第'+str(i+1)+'頁已下載')

manhua_download()