Python 使用Pycharm爬取网页中图片保存到指定目录

import re
import urllib.request
import ssl

ssl._create_default_https_context = ssl._create_unverified_context # Python 2.7.9 之后版本引入了一个新特性:当你urllib.urlopen一个 https 的时候会验证一次 SSL 证书 ,当目标使用的是自签名的证书时就会爆出该错误消息。

def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    html = html.decode('UTF-8')
    return html

def getImg(html):
    reg = r'src="(.*?\.jpg)"'
    image = re.compile(reg)
    imglist = re.findall(image,html)
    print(imglist)

    x = 0
    for image in imglist:
        pathName = "/Users/XLaws/Documents/Image/" + str(x) + ".jpg" #设置保存路径和文件名
        urllib.request.urlretrieve(image,pathName) #下载图片
        print("正在下载第:",x)
        x += 1

html = getHtml("http://588ku.com/")
getImg(html)
PyCharm本身不是一个用于自动化爬虫的工具,但它可以在Python环境下配合如BeautifulSoup、Scrapy等库来进行网页爬取。以下是使用Python和requests以及BeautifulSoup基本步骤来爬取网页图片保存指定文件夹的基本流程: 1. 安装必要的库: - 如果还没有安装`requests`,可以运行`pip install requests`。 - 对于解析HTML,推荐`beautifulsoup4`,安装命令为`pip install beautifulsoup4`。 2. 使用Python编写脚本: ```python import os import requests from bs4 import BeautifulSoup # 网页URL url = 'http://example.com' # 替换为你要抓取图片的实际网站URL # 设置目标文件夹 image_folder = "E:/images" if not os.path.exists(image_folder): os.makedirs(image_folder) def download_image(img_url): response = requests.get(img_url) if response.status_code == 200: with open(os.path.join(image_folder, img_url.split("/")[-1]), 'wb') as f: f.write(response.content) else: print(f"Failed to download image at {img_url}") # 解析网页获取图片链接 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') img_tags = soup.find_all('img') # 可能需要根据实际HTML结构调整 for img_tag in img_tags: img_url = img_tag['src'] download_image(img_url) print("图片下载完成.") ``` 3. 运行脚本:将上述代码复制到PyCharm的新项目里,设置好环境变量,然后通过Run菜单或快捷键运行。 注意:实际操作中可能遇到的问题包括反爬机制、动态加载图片、权限问题等。此外,遵守网站的robots.txt协议,尊重版权,合理使用网络资源。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值