腾讯爬虫python_Python爬虫,爬取腾讯漫画实战
先上個爬取的結果圖
最后的結果為每部漫畫按章節保存
運行環境
IDE VS2019
Python3.7
先上代碼,代碼非常簡短,包含空行也才50行,多虧了python強大的庫
importosimporttimeimportrequestsfrom selenium importwebdriverfrom lxml importetreedefgetChapterUrl(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 inli_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])defgetChapterFile(url,path1,path2):#path = os.path.join(path)
#漫畫名稱目錄
path=os.path.join(path1)if notos.path.exists(path):
os.mkdir(path)#章節目錄
path=path+'\\'+path2if notos.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 inrange(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
總結
以上是生活随笔為你收集整理的腾讯爬虫python_Python爬虫,爬取腾讯漫画实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 出租房子门对北,床头应该对哪?
- 下一篇: 怎么样才能让家里的窗帘更加美观?