先上個爬取的結果圖
最后的結果為每部漫畫按章節保存
?
?運行環境
IDE VS2019
Python3.7
Chrome、ChromeDriver
Chrome和ChromeDriver的版本需要相互對應
先上代碼,代碼非常簡短,包含空行也才50行,多虧了python強大的庫
import os import time import requests from selenium import webdriver from lxml import etree def getChapterUrl(url): headers = { " User-Agent " : " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 " } part_url = " http://ac.qq.com " res = requests.get(url, headers= headers) html = res.content.decode() el = etree.HTML(html) li_list = el.xpath( ' //*[@id="chapter"]/div[2]/ol[1]/li ' ) for li in li_list: for p in li.xpath( " ./p " ): for span in p.xpath( " ./span[@class='works-chapter-item'] " ): item = {} list_title = span.xpath( " ./a/@title " )[0].replace( ' ' , '' ).split( ' : ' ) if list_title[1].startswith(( ' 第 ' , ' 序 ' )): getChapterFile(part_url + span.xpath( " ./a/@href " )[0], list_title[0],list_title[1 ]) def getChapterFile(url,path1,path2): # path = os.path.join(path) # 漫畫名稱目錄 path= os.path.join(path1) if not os.path.exists(path): os.mkdir(path) # 章節目錄 path=path+ ' \\ ' + path2 if not os.path.exists(path): os.mkdir(path) chrome = webdriver.Chrome() # "http://ac.qq.com/ComicView/index/id/505435/cid/2" chrome.get(url) time.sleep( 4 ) imgs = chrome.find_elements_by_xpath( " //div[@id='mainView']/ul[@id='comicContain']//img " ) for i in range(0, len(imgs)): js = " document.getElementById('mainView').scrollTop= " +str((i) * 1280 ) chrome.execute_script(js) time.sleep( 3 ) print (imgs[i].get_attribute( " src " )) with open(path + ' \\ ' +str(i)+ ' .png ' , ' wb ' ) as f: f.write(requests.get(imgs[i].get_attribute( " src " )).content) chrome.close() print ( ' 下載完成 ' ) if __name__ == ' __main__ ' : getChapterUrl( ' http://ac.qq.com/Comic/ComicInfo/id/505435 ' )
簡單解釋
輸入一個漫畫的url即可爬取該漫畫所有的章節,由于是模擬用戶爬取的,所以速度方面有點慢,我試了下爬取銀魂前70章,用了1個半小時,代碼中的sleep可以適當簡短點已加快爬取的速度
付費的漫畫是沒有辦法爬取的
?
談一下過程中遇到的坑
騰訊的漫畫網站打開章節時沒有把所有圖片的url都加載出來,所以我在這里用的方式是使用selenium來模擬用戶操作,每次打開頁面以后使用js操作滾動條下拉
?
最后再貼下代碼庫,其實貼出的代碼已經是所有的代碼了
https://dev.azure.com/shenjuncaci/PythonTecentManhua
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
