python简单爬取图片

这里我们来简单爬取一下英雄联盟的英雄信息和英雄图片
代码如下:

import requests
import json
import re
import os

class Grab_img(object):
    hero_img_list = []

    def __init__(self,url):
        self.url = url


    def grab_id(self):
        response = requests.get(self.url)
        pat = r"\"keys\":(.+),\"data\""
        hero_id = json.loads(str(re.findall(pat, response.text))[2:-2])
        for i in hero_id:
            self.hero_img_list.append('http://ossweb-img.qq.com/images/lol/web201310/skin/big' + i + '000.jpg')



    def storage_img(self):
        for i in self.hero_img_list:
            root = "E://photo//"
            # 文件名
            path = root + i.split("/")[-1]

            # 判断根目录是否存在
            if not os.path.exists(root):
                os.mkdir(root)

            # 判断文件是否存在
            if not os.path.exists(path):
                r = requests.get(i)
                with open(path, "wb") as f:
                    f.write(r.content)
                    print("文件保存成功~~")
            else:
                print("文件已存在~~")



    def main(self):
        #获取英雄ID
        self.grab_id()

        #下载保存图片
        self.storage_img()


if __name__ == '__main__':
    try:
        t = Grab_img("http://lol.qq.com/biz/hero/champion.js")
        t.main()
    except:
        print("爬取出错啦~~~")

以上就是用python爬取lol图片的代码 下载后位置保存在 E://photo// 。

### 使用Python实现网页图片爬取 为了完成网页图片的抓取,可以采用`requests`库获取页面内容并使用正则表达式模块`re`或者BeautifulSoup解析HTML文档中的图像链接。对于`requests`库而言,这并非Python内置的一部分,因此需要通过命令行工具执行`pip install requests`来进行安装[^3]。 下面是一个简单的例子展示如何利用上述提到的技术栈来下载指定URL内的所有图片: ```python import os import re import requests from urllib.parse import urljoin, urlparse from bs4 import BeautifulSoup def download_images(url, folder='images'): try: response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') if not os.path.exists(folder): os.makedirs(folder) img_tags = soup.find_all('img') urls = [img['src'] for img in img_tags] for index, img_url in enumerate(urls): # Handle relative URLs by joining with base URL. full_img_url = urljoin(url, img_url) img_data = requests.get(full_img_url).content ext = os.path.splitext(urlparse(full_img_url).path)[1] file_name = f"{folder}/image_{index}{ext}" with open(file_name, 'wb') as handler: handler.write(img_data) print(f'Downloaded {file_name}') except Exception as e: print(f'Error occurred while downloading images from {url}:', str(e)) download_images('http://example.com/') # Replace this URL with the target website's address you want to scrape. ``` 这段脚本会访问给定网址,并尝试找到所有的`<img>`标签及其对应的源文件路径(`src`)属性值;接着它会对这些资源发起请求并将接收到的数据保存到本地磁盘上预先定义好的目录里。注意这里处理了相对路径的情况,确保能够正确拼接成完整的图片地址[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值