python - python imagedownloader,不能作为类在其他文件中工作
问题描述
这是我的第一个程序,它是一个“imagedownloader”,用户可以输入宽度和高度。当我在单个文件中运行我的代码而不创建类时,它可以工作。但是在尝试将其作为一个类并将其导入到主文件之后,它不再起作用了,但是没有错误。这就是我导入模块并创建对象的方式。
主文件:
from DownLoader import *
d = DownLoader("https://imga.biz/", 40, 40)
d.down()
下载模块:
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO
class DownLoader:
def __init__(self, url_, xx, yz):
self.url = url_
self.x = xx
self.y = yz
self.page = requests.get(self.url)
self.soup = BeautifulSoup(self.page.text, "html.parser")
self.images = self.soup.find_all("img")
self.images_src_array = []
self.src_old = ""
for i in self.images:
if i['src'][0:4] == "http": #check if its a https site
if i['src'] == self.src_old: #whether is the same image as last
continue
else:
self.images_src_array.append(i['src'])
self.src_old = i['src']
def down(self):
name = ""
index = 0
for img in self.images_src_array:
if self.check_image_size(img)[0] >= self.x and self.check_image_size(img)[1] >= self.y:
img_data = requests.get(img).content
with open(name + str(index) + ".jpg", 'wb') as handler:
handler.write(img_data)
print(str(index) + " : " + img)
index += 1
def check_image_size(self, url):
try:
img_data = requests.get(url).content
img = Image.open(BytesIO(img_data))
return img.size
except Exception:
return (0, 0)
没有类或导入的下载器,我试图转换为类:
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO
url = input("Enter Url: ")
x = int(input("insert width: "))
y = int(input("insert height: "))
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
images = soup.find_all("img")
images_src_array = []
src_old = ""
for src in images:
if src['src'][0:4] == "http": #check if its a https site
if src['src'] == src_old: #whether is the same image as last
continue
else:
images_src_array.append(src['src'])
src_old = src['src']
def download(images_src, width, height):
name = ""
index = 0
for img in images_src:
if check_image_size(img)[0] >= width and check_image_size(img)[1] >= height: #checks size and also if its image
img_data = requests.get(img).content
with open(name+str(index)+".jpg", 'wb') as handler:
handler.write(img_data)
print(str(index) + " : " + img)
index += 1
def check_image_size(url_link):
try:
data = requests.get(url_link).content
img = Image.open(BytesIO(data))
return img.size
except Exception:
return (0,0) #return for height and width
download(images_src_array, x, y)
print("\nfinish")
page.close()
解决方案
推荐阅读
- python - 如何使用具有不同特征的两个模型的集成学习作为输入?
- ffmpeg - 使用 ffmpeg 库转换流格式
- docker - 如何在 docker-compose.yml 中运行多个 shell 脚本
- jpa - 如何为不提供列名的存储过程调用定义 JPA SqlResultSetMapping?
- math - 线性回归 2 个因变量
- bash - 我需要通过 gitlab-ci 中的 ssh 将一个环境变量传递给 docker
- python - python REPL:仅显示完成选择的相关部分
- angular - 如何使用 AngularFire 从 FireBase 存储中获取文件列表
- c++ - Pybind11:如何为结构成员变量分配默认值?
- python - Kivy:如何检查拖动行为项的位置