python3爬取网页图片

爬虫思路

一、确定要爬取的页面——确定目标
1.打开含有图片的网页
2.打开页面代码:右键——>查看源代码
二、分析网页内容
1.url路径格式
2.数据格式(常见 html文档 格式)
3.网页数据编码格式(常见 utf-8)
三、代码实现、运行、修改

代码实现

一、请求网页(网页地址 url)

1.导入网络请求库:import requests

2.请求网页地址:response = requests.get(url)

3.检查是否请求成功(两种方法):

  • 打印输出网页的所有数据:print(response.text)
  • 打印 返回 请求状态码:print(response.raise_for_satus())——None表示请求成功

二、解析文档树

1.导入Beautiful Soup库import bs4

  • Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,解析分析网页数据,提取想要的数据
  • html_parser:bs4自带的解析器
  • lxml:需要下载安装的解析器

2.遍历文档树,解析搜索数据soup = bs4.BeautifulSoup(response.text,'html_parser')

3.找到要爬取的数据节点(图片节点)image_urls = soup.select(".image-list-link img")

4.判断当前节点下是否有图片;如果有,提取所有‘src’,所有图片存储路径download_url :

  • if not image_url in image_urls

    print("当前节点下,没图片!")

  • else

    for image_url in image_urls:

      download_url = image_url.get('src')

      print("下载图片的路径:", download_url)

三、存储爬取的数据

     1.导入处理文档的库import os

     2.找到分割点,剔除路径,提取图片名称 file_name

      split = download_url.split('/')

      file_name = os.path.basename(split[len(split)-1])

      print("元素:", file_name)

     3.构建本地保存,存储图片的文件夹 image

      dir_name = 'image'

      os.makedirs(dir_name,exist_ok=True)

     4.返回完整的文件本地存储路径 file_path 

      file_path = os.path.join(dir_name, file_name)

      print("file_path:",file_path)

     5.检查当前图片路径是否存在,不存在就请求网上图片的地址,并将图片存储到本地路径中

      if not os.path.exists(file_path):

      image_url_path = requests.get("https:" + download_url)

     6.检查当前网址是否请求成功,两种方法:1.print,输出<Response [200]>表示请求成功;2.status状态码,输出None

      print("请求", image_url_path)

      image_url_path.raise_for_status()

     7.打开文件夹中的文件(file_path);"wb"二进制读写模式

      image_file = open(file_path,"wb")

     8.存储每一张图片,获取网页中N个值(随意指定要获取的数目N,这里N=1000)

      for images in image_url_path.iter_content(1000):

       9.把每次遍历的文件,全部写入文件中

        image_file.write(images)

       10.io流,在用完数据后,关闭数据流资源

        image_file.close()

猜你喜欢

转载自www.cnblogs.com/ruyingsuixing/p/9050270.html
今日推荐