【python爬虫】—图片爬取

图片爬取

需求分析

Python实现

  • 获取待爬取网页
python 复制代码
def get_htmls(pages=list(range(2, 5))):
    """获取待爬取网页"""
    pages_list = []
    for page in pages:
        url = f"https://pic.netbian.com/4kfengjing/index_{page}.html"
        response = requests.get(url)
        response.encoding = 'gbk'
        pages_list.append(response.text)
    return pages_list
get_htmls(pages=list(range(2, 5)))
  • 获取所有图片,并下载
python 复制代码
def get_picturs(htmls):
    """获取所有图片,并下载"""
    for html in htmls:
        soup = BeautifulSoup(html, 'html.parser')
        pic_li = soup.find('div', id='main').find('div', class_='slist').find('ul', class_='clearfix')
        image_path = pic_li.find_all('img')
        for file in image_path:
            pic_name = './practice05/' + file['alt'].replace(" ",'_') + '.jpg'
            src = file['src']
            src = f"https://pic.netbian.com/{src}"

            response = requests.get(src)

            with open(pic_name, 'wb') as f:
                f.write(response.content)
                print("图片已下载并保存为:{}".format(pic_name))
                
htmls = get_htmls(pages=list(range(2, 5)))
get_picturs(htmls)
  • 爬取结果展示

相关推荐
伊玛目的门徒30 分钟前
告别 OpenAI SDK:如何使用 Python requests 库调用大模型 API(例如百度的ernie-4.5-turbo)
python·openai·requests·大模型调用·ernie-4.5-turbo
ningmengjing_36 分钟前
webpack打包方式
前端·爬虫·webpack·node.js·逆向
sinat_602035362 小时前
模块与包的导入
运维·服务器·开发语言·python
计算机学姐2 小时前
基于Python的旅游数据分析可视化系统【2026最新】
vue.js·后端·python·数据分析·django·flask·旅游
恋雨QAQ2 小时前
python函数和面向对象
开发语言·python
天雪浪子2 小时前
Python入门教程之逻辑运算符
开发语言·python
张子夜 iiii2 小时前
实战项目-----在图片 hua.png 中,用红色画出花的外部轮廓,用绿色画出其简化轮廓(ε=周长×0.005),并在同一窗口显示
人工智能·pytorch·python·opencv·计算机视觉
gongzemin2 小时前
Django入门2--设置数据库 admin
python·django