DeviantArt Scraper


Requrements

     requirements.txt  
###### Required Packages ######
selenium
bs4
requests

Script

  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
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
from bs4 import BeautifulSoup
from queue import Queue
from threading import Thread, Lock
import collections
import datetime
import time
import os
import pathlib
import requests
import subprocess

images  = []
img_num = 0
workers = 20
threads = []
tasks   = Queue()
lock    = Lock()

def welcome_message():
    now = datetime.datetime.now()
    today = now.strftime("%A • %B %e • %H:%M • %Y")
    print('\n  DeviantArt Scraper')
    print('\n  DATE:  ' + today)

def get_driver():
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=options)
    return driver

def get_username(d):
    global username
    html = d.page_source
    soup = BeautifulSoup(html, 'html.parser')
    username = soup.find(class_='gruserbadge').find('a').get_text()

def get_thumb_links(q):
    d = get_driver()
    d.get('https://heywyd.deviantart.com/gallery/')
    unique_img = scroll_page_down(d)
    time.sleep(0.5)
    for img in unique_img:
        q.put(img)
    global expected_img_num
    expected_img_num = str(len(unique_img))
    get_username(d)
    print('  Unique images found = ' + expected_img_num)
    print('  Artist = ' + username + "\n")
    time.sleep(0.5)
    d.close()

def scroll_page_down(d):
    SCROLL_PAUSE_TIME = 1.5
    last_height = d.execute_script("return document.body.scrollHeight")
    while True:
        d.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(SCROLL_PAUSE_TIME)
        new_height = d.execute_script("return document.body.scrollHeight")
        im = d.find_element_by_class_name('folderview-art')
        links = im.find_elements_by_class_name('torpedo-thumb-link')
        for link in links:
            l = link.get_attribute('href')
            images.append(l)
        unique_img = list(set(images))
        time.sleep(0.5)
        if new_height == last_height:
            break
        last_height = new_height
    return unique_img

def get_full_image(l):
    s = requests.Session()
    h = {'User-Agent': 'Firefox'}
    soup = BeautifulSoup(s.get(l, headers=h).text, 'html.parser')
    title = ''
    link = ''
    try:
        link = soup.find('a', class_='dev-page-download')['href']
    except TypeError:
        try:
            link = soup.find('img', class_='dev-content-full')['src']
            title = soup.find('a',
                                 class_='title').text.replace(' ', '_').lower()
        except TypeError:
            try:
                link = age_restricted(l)
            except (WebDriverException, AttributeError):
                link = age_restricted(l)
        pass
    req = s.get(link, headers=h)
    time.sleep(0.1)
    download_now(req,title)
    url = req.url
    ITuple = collections.namedtuple('ITuple', ['u', 't'])
    it = ITuple(u=url, t=title)
    return it

def age_restricted(l):
    d = get_driver()
    d.get(l)
    time.sleep(0.8)
    d.find_element_by_class_name('datefields')
    d.find_elements_by_class_name('datefield')
    d.find_element_by_id('month').send_keys('01')
    d.find_element_by_id('day').send_keys('01')
    d.find_element_by_id('year').send_keys('1991')
    d.find_element_by_class_name('tos-label').click()
    d.find_element_by_class_name('submitbutton').click()
    time.sleep(1)
    img_lnk = d.find_element_by_class_name('dev-page-download')
    d.get(img_lnk.get_attribute('href'))
    time.sleep(0.5)
    link = d.current_url
    d.close()
    return link

def name_format(url,title):
    if url.find('/'):
        name =  url.rsplit('/', 1)[1]
        p1 = name.split('-')[0]
        p2 = name.split('-')[1].split('.')[1]
        name = p1 + '.' + p2
    if title != '':
        name = title + '.png'
    return name

def download_now(req,title):
    url = req.url
    name = name_format(url,title)
    pathlib.Path('{}.deviantart.com'.format(username)).mkdir(parents=True,
                                                             exist_ok=True)
    with open(os.path.join('{}.deviantart.com/'.format(username),
                                               '{}'.format(name)),'wb') as file:
        file.write(req.content)

def save_img(url):
    try:
        with open('{}-gallery.txt'.format(username), 'a+') as file:
            file.write(url + '\n')
    except:
        print('An write error occurred.')
        pass

def worker_thread(q, lock):
    while True:
        link = q.get()
        if link is None:
            break
        p = get_full_image(link)
        url = p.u
        title = p.t
        name = name_format(url, title)
        with lock:
            global img_num
            img_num += 1
            save_img(url)
            print('Image ' + str(img_num) + ' - ' + name)
        q.task_done()

def main():
    welcome_message()
    start = time.time()
    get_thumb_links(tasks)

    for i in range(workers):
         t = Thread(target = worker_thread, args = (tasks, lock))
         t.start()
         threads.append(t)
    tasks.join()
    for _ in range(workers):
        tasks.put(None)
    for t in threads:
        t.join()

    folder_size = subprocess.check_output(['du','-shx',
             '{}.deviantart.com/'.format(username)]).split()[0].decode('utf-8')
    print('\n  Total Images: ' + str(img_num) + ' (' + str(folder_size) + ')')
    print('  Excepted: ' + expected_img_num)
    end = time.time()
    print('  Elapsed Time: {:.4f}\n'.format(end-start))

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print()