导语:
哈喽,哈喽~当有人给你安利了一部超级好看的漫画时。
你点进去看了一下,这画风,这剧情,代入感太强我现在宣布我就是女主了。
但是看着看着,要vip你又没有时,这是什么人间疾苦啊!我的女主光环呢?
正文:
下面小编使用python爬取漫画,此次代码以一个小型的网站来作为练手,其他的和该思路差不多大致相同,仅供参考。
https://m.gufengmh8.com/
打开这个网址后,让我们点击搜索进行相关的漫画搜索。截图为搜索页面,可以看到网址为:
https://m.gufengmh8.com/search/?keywords=斗罗大陆
keywords后面跟的就是要搜索的内容,然后我们获取url的方式就可以是这样。
"https://m.gufengmh8.com/manhua/search/?keywords="+str(input("搜索漫画:"))#input让用户输入,获取输入内容
浏览器按f12进入代码调试,单击下图位置,然后可以看到class为itemBox,所以我们只需要获取到这个页面所有的class为itemBox的div,就可以获取每本漫画的所有信息。
import math
import threading
import time
import os
import requests
from bs4 import BeautifulSoup
from urllib3.connectionpool import xrange
#根据url获取对应页面的所有内容,然后返回
def get_document(url):
# print(url)
try:
get = requests.get(url)#打开连接
data = get.content#获取内容
get.close()#关闭连接
except:#抛异常就重试
time.sleep(3)#睡眠3秒,给网页反应时间
try:再次获取
get = requests.get(url)
data = get.content
get.close()
except:
time.sleep(3)
get = requests.get(url)
data = get.content
get.close()
return data
#下载漫画
def download_img(html):
soup = BeautifulSoup(html)#BeautifulSoup和request搭配使用更佳呦
itemBox = soup.find_all('div', attrs={'class': 'itemBox'})#find_all返回的是一个list
for index, item in enumerate(itemBox):#遍历itemBox,index是当前项list的下标,item是内容
itemTxt = item.find('div', attrs={'class': 'itemTxt'})#因为只有一个,所以itemBox中只有一个itemTxt所以这次我们用find
a = itemTxt.find('a', attrs={'class': 'title'}).text[]
print(str(index+1)+'.'+a)
# download_img(get_document("https://m.gufengmh8.com/search/?keywords="+str(input("搜索漫画:"))))
download_img(get_document("https://m.gufengmh8.com/search/?keywords=完美世界"))#这个就不解释了吧
现在我们基本实现了搜索功能,这已经算是个简单爬虫了,之后让用户输入书籍序号,然后下载。
def download_img(html):
chapter_url_list=[]
soup = BeautifulSoup(html)#BeautifulSoup和request搭配使用更佳呦
itemBox = soup.find_all('div', attrs={'class': 'itemBox'})#find_all返回的是一个list
for index, item in enumerate(itemBox):#遍历itemBox,index是当前项list的下标,item是内容
itemTxt = item.find('div', attrs={'class': 'itemTxt'})#因为只有一个,所以itemBox中只有一个itemTxt所以这次我们用find
a = itemTxt.find('a', attrs={'class': 'title'})
chapter_url = a['href']
chapter_url_list.append(chapter_url)#把所有书的url存起来
print(str(index+1)+'.'+a.text)
number = int(input('请输入漫画序号'))
chapter_html = BeautifulSoup(get_document(chapter_url_list[number-1]))#因为打印的序号和list的索引是相差1的,所以输入的序号减一获取对应书的url,再根据url获取到目录页面
ul = chapter_html.find('ul', attrs={'id': 'chapter-list-1'})#获取到ul
li_list = ul.find_all('li')#获取其中所有li
for li in li_list:#遍历
li_a_href = li.find('a')['href']#注意这里获取到的url是不完整的/manhua/buhuochongwuniangdezhengquefangfa/1000845.html
现在我们随便点入一个章节获取到漫画图片的位置
接着我们获取到了所有的漫画图片src,现在就只需要把他下载下来了,先创建目录。
path = "d:/SanMu/"+book_name+'/'+li.text.replace('\n', '')
if not os.path.exists(path):
os.makedirs(path)
然后下载,很简单吧!
open(path+'/'+str(i)+'.jpg', 'wb').write(get_document(img_src))#保存到d:/SanMu/书名/章节名/0.jpg
结尾:
好啦文章就分享到这里就结束啦~
大家喜欢的记得点点赞,需要完整的项目源码的私信我即可哟!点击这行文字也是可以的哦!