Python爬取网站图片(爬虫入门demo)

代码功能:

爬取网站的教师图片,在用户主机上创建好PNG文件夹保存共110张图片,同时把每张图片的老师介绍内容写入H3.txt文件中。

实现思路:

打开该网页后用F12查看网页的html原代码,发现图片所在的标签ul下,但不是唯一,通过find_all函数筛选发现得到的列表的第一个元素就是我们所需要的,最后用for循环遍历提取出每个图片对应的src再通过open的二进制格式把图片写入PNG目录下,同理h3的获得也遵循该思路。需要注意的是环境中除了要安装import对应的包还要安装pip install html5lib

代码实现:

import requests
import os,sys
import shutil
from bs4 import BeautifulSoup

response = requests.get(url="http://www.mobiletrain.org/teacher/")

def get_resource_path(relative_path): # 利用此函数实现资源路径的定位
    if getattr(sys, "frozen", False):
        base_path = sys._MEIPASS # 获取临时资源
        print(base_path)
    else:
        base_path = os.path.abspath(".") # 获取当前路径
    return os.path.join(base_path, relative_path) # 绝对路径

if response.status_code == 200:    #404和405是页面消失报错
    print("连接成功!")
    # 设置返回源码的编码格式
    response.encoding = "UTF-8"
    # print(type(response.text))
    html = BeautifulSoup(response.text,"html5lib")
    ul=html.find_all("ul",attrs={"class":"clear"})[0]#找唯一的父节点再找子节点,或者找出后得到列表取第一个
    li_list = ul.find_all("li")

    i = 0
    PNG=get_resource_path('png')   #判断是否有PNG目录存在,存在则删除再创建,避免使用的时候报错
    if os.path.exists(PNG):
        shutil.rmtree(PNG)
    png = os.mkdir(PNG)

    for li in li_list:
        i += 1
        img_src = li.find("img")["src"]
        response_child = requests.get(img_src)
        fileWriter = open(get_resource_path(os.path.join("png", "{}.png".format(i))), "wb")
        fileWriter.write(response_child.content)
        h3 = li.find("h3").text
        text=open('H3.txt','a',encoding='utf-8')
        text.write(h3+'\n')
        text.close()
else:
    print("连接失败!")



猜你喜欢

转载自blog.csdn.net/weixin_56115549/article/details/126653567