鱼C论坛

 找回密码
 立即注册
查看: 1563|回复: 0

[作品展示] 新手爬取妹子图,绝对领域!

[复制链接]
发表于 2020-5-15 00:24:48 | 显示全部楼层 |阅读模式

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

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

x
  1. #导入爬虫所需要的模块
  2. from bs4 import BeautifulSoup
  3. import requests
  4. import os
  5. import time
  6. #获取网页信息
  7. def get_page(url):
  8.         try:
  9.                 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
  10.                 }
  11.                 response = requests.get(url,headers=headers)
  12.                 if response.status_code == 200:
  13.                         return response.text
  14.                 return None
  15.         except RequestException:
  16.                 return None

  17. #解析主页,返回所有套图标题和链接
  18. def parse_page(html):
  19.         soup = BeautifulSoup(html,'lxml')
  20.         title = soup.find_all('a',{'rel':'bookmark'})
  21.         for t in title:
  22.                         yield [t.get_text(),t.get('href')]#生成一个列表

  23. #解析主页套图内图片链接                       
  24. def parse_title(html):
  25.         soup = BeautifulSoup(html,'lxml')
  26.         allimg = soup.find_all('img',{'border':'0'})
  27.         for img in allimg:
  28.                         yield img.get('src')

  29. def main(pagenumber):       
  30.         url = 'https://www.jdlingyu.mobi/collection/meizitu/page/1' + str(pagenumber)
  31.         html = get_page(url)
  32.         for p in parse_page(html):
  33.                 imageurl = get_page(p[1])
  34.                 folder_path = './photo/' + p[0] + '/'#以标题命名文件夹民称
  35.                 if os.path.exists(folder_path) == False:  # 判断文件夹是否已经存在
  36.                         os.makedirs(folder_path)
  37.                 for index,i in enumerate(parse_title(imageurl)):
  38.                         down = requests.get(i)
  39.                         img_name = folder_path + str(index) +'.png'
  40.                         with open(img_name, 'wb') as file:  # 以byte形式将图片数据写入
  41.                                 file.write(down.content)
  42.                                 file.flush()
  43.                         file.close()  # 关闭文件

  44. if __name__ == '__main__':
  45.         for i in range(2):#多少页自己决定
  46.                 main(i)
  47.                 time.sleep(1)
复制代码


刚入坑不久,尝试写了一个妹子图的爬虫。已经实现了翻页多页爬取,分标题存放图片文件。思路是先爬主页上套图的标题和链接,再解析链接中的图片,利用生成的列表为下载图片过程中创建以标题命名文件。爬单页速度55-60s左右,感觉代码可以优化,求指点。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-19 07:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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