鱼C论坛

 找回密码
 立即注册
查看: 2226|回复: 8

[萌新报道] python爬取某网站图片

[复制链接]
发表于 2020-4-10 22:03:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import os


  5. def get_url_list(url):

  6.     """返回某一页url列表"""
  7.     response = requests.get(url).text
  8.     soup = BeautifulSoup(response,'html.parser')
  9.     href1 = re.compile('https://www.meitulu.com/item/')
  10.     url_list = []
  11.     for class_name in soup.find_all('a',href = href1):
  12.         ele = class_name.get('href')
  13.         if ele not in url_list:
  14.             url_list.append(class_name.get('href'))

  15.     # url_list 各组图片总列表
  16.     for jiangchong in url_list:
  17.         print(jiangchong)

  18.     return url_list


  19. def img_num_list(url_list):

  20.     """返回url_list 中各组图片数量列表"""
  21.     num_list = []
  22.     for name in url_list:
  23.         response = requests.get(name)
  24.         response.encoding = response.apparent_encoding
  25.         soup = BeautifulSoup(response.text, 'html.parser')
  26.         str1 = soup.find_all(string=re.compile('图片数量'))
  27.         num = int(re.findall('[0-9][0-9]', str1[0])[0])
  28.         num_list.append(num)
  29.     # print(num_list)
  30.     return num_list


  31. def img_list(url,num):
  32.     """返回一组图片url 列表"""
  33.     if num % 4 == 0:
  34.         last_page = num // 4
  35.     else:
  36.         last_page = num // 4 + 1

  37.     imglist = []
  38.     re = requests.get(url).text
  39.     soup = BeautifulSoup(re, 'html.parser').center
  40.     # 特殊的第一页
  41.     for kk in soup.find_all('img'):
  42.         imglist.append(kk.get('src'))
  43.     # 第二页及以后
  44.     for i in range(2, last_page+1):
  45.         re = requests.get(url.rstrip('.html') + f'_{i}' + '.html').text
  46.         soup = BeautifulSoup(re, 'html.parser').center
  47.         for k in soup.find_all('img'):
  48.             imglist.append(k.get('src'))
  49.     return imglist


  50. def save_image_list(imglist,url):
  51.     """保存一组图片"""
  52.     for i in imglist:
  53.         img_name = i.split('/')[-2] + '-' + i.split('/')[-1]
  54.         f = open(r"E://meitulu//%s//%s" % (url.split('/')[-2] , img_name) , 'wb')
  55.         r = requests.get(i)
  56.         f.write(r.content)
  57.         f.close()


  58. def other_pages(url):
  59.     re = requests.get(url)
  60.     re.encoding = re.apparent_encoding
  61.     soup = BeautifulSoup(re.text, 'html.parser')
  62.     title = soup.title.string
  63.     if title != "美图录-您访问的信息已删除或不存在":
  64.         return True
  65.     else:
  66.         return False


  67. def papapa(url):
  68.     file_name = url.split('/')[-2]
  69.     os.mkdir(f"E://meitulu//{file_name}")
  70.     count2 = 2
  71.     while other_pages(url):
  72.         url_list = get_url_list(url)
  73.         num_list = img_num_list(url_list)
  74.         count = 0
  75.         for count3 in url_list:
  76.             try:
  77.                 presave_img_list = img_list(count3,num_list[count])
  78.                 save_image_list(presave_img_list,url)
  79.             except:
  80.                 print('爬虫失败 ' + url + ' ' + count3)
  81.             finally:
  82.                 count += 1
  83.         if url.split('/')[-1] == f"{count2}.html":
  84.             url = url.replace(f"{count2}.html", f"{count2 + 1}.html")
  85.             count2 += 1
  86.         else:
  87.             url = url + f'{count2}.html'



  88. papapa("https://www.meitulu.com/t/xiameijiang/")
复制代码



菜鸟写了一个小爬虫,请各位大佬指教
食用方法:进入例子中的网站,进入某一位模特的主页,将其主页中第一页的url输入函数papapa(),就可以获得她的所有图片.
                注意,会在E盘创建一个文件夹,不能有重名文件夹哦.

结果图展示

结果图展示
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-4-12 08:54:16 | 显示全部楼层
本帖最后由 chen971130 于 2020-4-12 09:11 编辑

更新了一下代码,这次不会每次都判断该页url是否存在了,效率应该会高一些。
使用注意事项:
(1)要安装所有使用的库
(2)要先手动在E盘下新建名为  meitulu  的文件夹。每次执行程序会在该文件夹下自动创建 模特名的文件夹,每次运行要查看是否有重名文件,有的话要删除。如例中为“E://meitulu//nixiaoyao”,如果中途失败,再次爬取同一模特图片的话,要保证‘E://meitulu//’下没有名为‘nixiaoyao’的文件夹。
(3)使用方法:进入https://www.meitulu.com/,选择一位喜欢的模特,点击她的名字进入她的主页,将该页的网址填入主函数(注意是字符串)。
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import os


  5. def get_url_page_list(url):
  6.     """如果有多页,返回各页的url列表"""
  7.     a = BeautifulSoup(requests.get(url).text,'html.parser').center.select('a')
  8.     url_list = []
  9.     for i in a:
  10.         url1 = i.get('href')
  11.         if url1 not in url_list and  url1 != None:
  12.             url_list.append(url1)
  13.     if not url_list:
  14.         url_list.clear()
  15.         url_list.append(url)
  16.     return url_list


  17. def get_url_list(url):
  18.     """返回某一页所有图片组的url列表"""
  19.     response = requests.get(url).text
  20.     soup = BeautifulSoup(response,'html.parser')
  21.     href1 = re.compile('https://www.meitulu.com/item/')
  22.     url_list = []
  23.     for class_name in soup.find_all('a',href = href1):
  24.         ele = class_name.get('href')
  25.         if ele not in url_list:
  26.             url_list.append(class_name.get('href'))
  27.     # url_list 一页上各组总列表
  28.     for jiangchong in url_list:
  29.         print(jiangchong)
  30.     return url_list


  31. def get_img_list(url):
  32.     """返回一组中所有图片的url列表"""
  33.     imglist = []
  34.     # 处理每组中的第一页
  35.     re = requests.get(url).text
  36.     soup = BeautifulSoup(re, 'html.parser').center
  37.     for first_page_img in soup.find_all('img'):
  38.         imglist.append(first_page_img.get('src'))
  39.     # 获得该组图片最大页数
  40.     max_page = get_pages(url)
  41.     # 处理第二页及以后
  42.     new_url = url.rstrip('.html') + f'_1' + '.html'
  43.     for i in range(2,max_page+1):
  44.         new_url = new_url.replace(f"{i-1}.html",f"{i}.html")
  45.         soup = BeautifulSoup(requests.get(new_url).text,'html.parser').center
  46.         for not_first_pages in soup.find_all('img'):
  47.             imglist.append(not_first_pages.get('src'))
  48.     return imglist


  49. def save_img(imglist, url):
  50.     """保存一组图片"""
  51.     for i in imglist:
  52.         img_name = i.split('/')[-2] + '-' + i.split('/')[-1]
  53.         f = open(r"E://meitulu//%s//%s" % (url.split('/')[-2] , img_name) , 'wb')
  54.         r = requests.get(i)
  55.         f.write(r.content)
  56.         f.close()


  57. def get_pages(url):
  58.     # 获得一组图片的页数
  59.     res = requests.get(url)
  60.     res.encoding = res.apparent_encoding
  61.     soup = BeautifulSoup(res.text,"html.parser").find_all('center')
  62.     num = re.findall("\d\d",soup[1].text) + re.findall("\d",soup[1].text)
  63.     numm = []
  64.     for i in num:
  65.         numm.append(int(i))
  66.     return max(numm)


  67. def main(url):
  68.     """主函数"""
  69.     file_name = url.split('/')[-2]
  70.     os.mkdir(f"E://meitulu//{file_name}")
  71.     url_page_list = get_url_page_list(url)
  72.     for i in url_page_list:
  73.         url_list = get_url_list(i)
  74.         for count3 in url_list:
  75.             try:
  76.                 presave_img_list = get_img_list(count3)
  77.                 save_img(presave_img_list, url)
  78.             except:
  79.                 print('爬虫失败 ' + url + ' ' + count3)


  80. main("https://www.meitulu.com/t/nixiaoyao/")
复制代码
v2-a837bfd8ebd4fc7b63c65c4dde99be36_720w.jpg
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-11 00:06:37 | 显示全部楼层
为什么我复制楼主的代码总是会出现各种各样的Bug
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-11 09:03:37 | 显示全部楼层
为什么是新人报道。。。不应该是Python交流吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-11 09:04:09 | 显示全部楼层
神盾369 发表于 2020-4-11 00:06
为什么我复制楼主的代码总是会出现各种各样的Bug

你应该是没有安装requests
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-12 09:13:22 | 显示全部楼层
神盾369 发表于 2020-4-11 00:06
为什么我复制楼主的代码总是会出现各种各样的Bug

我更新了代码和使用事项,你试试吧,记得给反馈哦
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-12 09:14:42 | 显示全部楼层
乘号 发表于 2020-4-11 09:03
为什么是新人报道。。。不应该是Python交流吗

哈哈哈我也不知道在哪儿发,就随便找了个新手区,python交流那儿图片没有审核过
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-12 09:53:59 From FishC Mobile | 显示全部楼层
为什么学习python,除了脱发,还影响身体?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-13 10:40:37 | 显示全部楼层
zcyr1121 发表于 2020-4-12 09:53
为什么学习python,除了脱发,还影响身体?

双重打击
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 13:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表