-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomImageDownloader.py
More file actions
241 lines (180 loc) · 7.74 KB
/
CustomImageDownloader.py
File metadata and controls
241 lines (180 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# ================================ Made by: "USBEN" ========================================
# This program is a custom image downloader , this was only made for specific website.
# Only to be used as a reference on how to use Web parsers like BEAUTIFUL SOUP and SELENIUM
# Replace SAMPLETEXTS with your stuff , it might work.
# ==========================================================================================
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
import re
import urllib.parse as urlparse
import requests
from bs4 import *
# url = "https://wallpapers.com/minimalist"
# ==============EXAMPLE FUNCTIONS==================================
def joinurl(baseurl, path): # Joins url (needs work)
return '/'.join([baseurl, path.lstrip("/")])
def RootDomain(url): # Generates root domain to attach with trailing URLs
URLsplit = urlparse.urlsplit(url)
# print("URL data: ", URLsplit)
rootURL = URLsplit.netloc
URLscheme = URLsplit.scheme+":/"
# URLcombined = urlparse.urljoin(str(URLscheme), rootURL)
# print(URLcombined)
URLcombined = joinurl(URLscheme, rootURL)
return URLcombined
def GetLinks(url): # (NOT-USED-FUNCTION) Just kept this function as a example of BeautifulSoup useage
startLinks = []
imageDatalinks = []
imageDataDictionary = {}
pass1counter = 0
urlParsed = ParseHTML(url, "link")
# first pass to get high resolution links
for item in urlParsed.find_all("a"):
try:
itemparse = ParseHTML(item, "string")
if(itemparse.a.attrs.__contains__("class")):
if(itemparse.a["class"].__contains__("image_wrapper")):
pass1counter += 1
tailURL = itemparse.a["href"]
fullURL = joinurl(RootDomain(url), tailURL)
startLinks.append(fullURL)
#print(fullURL, "\n")
except:
continue
print("[PASS1]Total Links: ", pass1counter)
# Get image data link
for item in startLinks:
itemparse = ParseHTML(item, "link")
for item in itemparse.find_all("img"):
itemparse = ParseHTML(item, "string")
try:
if(itemparse.img["alt"].__contains__("SAMPLETEXT")):
link = itemparse.img["src"]
name = RegexName(link)
imageDataDictionary.update({name: link})
imageDatalinks.append(link)
print(link)
except:
continue
# =================================================================
def SoupImageLinks(linkList): # (WAY FASTER -USE THIS) over SeleniumImageLinks function
print("Started SoupImageLinks(This takes a while please wait)...")
imageLinks = []
for item in linkList:
itemparse = ParseHTML(item, "link")
for item in itemparse.find_all("img"):
itemparse = ParseHTML(item, "string")
try:
if(itemparse.img["alt"].__contains__("SAMPLE TEXT")):
link = itemparse.img["src"]
# name = RegexName(link)
# imageDataDictionary.update({name: link})
imageLinks.append(link)
# print(link)
except:
continue
WriteToFile("finallinks.txt", imageLinks)
def ParseHTML(content, type): # Returns Parsed HTML data
try:
if(type == "link"):
getURL = requests.get(content)
parse = BeautifulSoup(getURL.text, "html.parser")
elif(type == "string"):
getURL = str(content)
parse = BeautifulSoup(getURL, "html.parser")
else:
print("Invalid type specified.")
return
return parse
except:
print(
"Something went wrong in ParseHTML. Make sure the link starts with (http[s]://).")
def WriteToFile(filename, data): # Writes text data to file
with open(os.path.join(os.getcwd(), filename), "w+", encoding="utf-8") as file:
file.write(str(data))
print("Data written to ", filename, ".\n")
def RegexName(urlData): # Custom regex to get filename in link
patternRegex = re.compile("[0-9]+.jpg")
resultRegex = patternRegex.findall(urlData)
returnResult = resultRegex[0].replace(".jpg", ".webp")
return returnResult
def SeleniumSetup(): # Selenium driver setup with headless option
driverOptions = webdriver.FirefoxOptions()
driverOptions.headless = True
driver = webdriver.Firefox(options=driverOptions)
return driver
def GetInitialLinks(url): # Extract links from the landing page provided
driver = SeleniumSetup()
driver.get(url)
mainlinks = []
# Main links extraction
targetElement = driver.find_elements(
By.XPATH, "//a[@class='SAMPLE_TEXT']")
for all in targetElement:
mainlink = all.get_attribute("href")
# print(mainlink)
mainlinks.append(mainlink)
WriteToFile("startlinks.txt", mainlinks)
# (SLOW ASF, USE Beautiful soup version) Extract high-resolution image links
def SeleniumImageLinks(linkList):
imagelinkList = []
driver = SeleniumSetup()
# Getting content links
for item in linkList:
parselink = driver.get(item)
targetelement = driver.find_element(
By.XPATH, "//img[@alt='SAMPLE TEXT']")
finallink = targetelement.get_attribute("src")
# print(finallink)
imagelinkList.append(finallink)
WriteToFile("finallinks.txt", imagelinkList)
def ReadFileData(name): # Reads file and returns as the respective data type
with open(name, "r") as file:
fileData = eval(file.read())
return fileData
# Downloads image by accessing link with custom header data
def DownloadImage(url, imageName):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36", "referer": "https://www.[[SAMPLETEXT]].com/"}
# Headers needed to bypass 403 Forbidden errors
urlrequest = requests.get(url, headers=headers)
imagePath = os.path.join(os.getcwd(), imageName)
try:
with open(imagePath, "wb") as imageFile:
imageFile.write(urlrequest.content)
print("Image ", imageName, " downloaded.")
except:
print("Image not downloaded. Check URL or directory.")
def DownloadAll(folderName, linkList): # Custom function to bulk download all images
try:
os.mkdir(folderName)
print(folderName, " folder created.")
except:
print("Folder already exists.")
for item in linkList:
DownloadImage(item, os.path.join(folderName, RegexName(item)))
def CoreLoop(url, index):
# === CORE-LOOP======
print("=== Started work on Page: ", index, " ====")
GetInitialLinks(url)
print("Initial page links obtained...")
print("Getting main links...")
firstData = ReadFileData("startlinks.txt")
SoupImageLinks(firstData)
print("Main image links obtained...")
secondData = ReadFileData("finallinks.txt")
folderName = "Page "+index
DownloadAll(folderName, secondData)
print("\nPage: ", index, " cleared.\n")
# ====================
def PageIndexer(startPoint, loopLength):
for i in range(startPoint, loopLength):
iteratedURL = "[[SAMPLE TEXT]]" + \
str(i)
CoreLoop(iteratedURL, str(i))
def MAIN():
print("\n---IMAGE DOWNLOADER STARTED---\n")
# PageIndexer(31, 33)
# DownloadAll("Page 30", ReadFileData("finallinks.txt"))
MAIN()