-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
134 lines (111 loc) · 4 KB
/
main.py
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
from bs4 import BeautifulSoup
from threading import Thread
from queue import Queue
import requests
import warnings
import logging
import os
logging.basicConfig(
format = '%(asctime)s %(levelname)-8s %(message)s',
level = logging.INFO,
datefmt = '%Y-%m-%d %H:%M:%S')
def nextn(l, n):
if n == 0:
return next(l)
return next(x for i, x in enumerate(l) if i == n)
url = 'https://commons.wikimedia.org'
extensions = set({'jpg', 'jpeg', 'png'})
def add(elem):
global paths
try:
if not elem is None:
href = elem['href']
if not href is None:
if href not in hrefs:
hrefs.add(href)
paths.put(href)
except Exception as e:
warnings.warn("Unexpected exception occured when trying to add the element %s: %s" % (str(elem), str(e)), UserWarning)
def worker():
global found, fails
while True:
# Fetch page
try:
path = paths.get()
link = url + path
resp = requests.get(link)
html = resp.content
soup = BeautifulSoup(html, features = 'html.parser')
except Exception as e:
warnings.warn("Unexpected exception occured when trying to fetch %s: %s" % (link, str(e)))
fails.append((path, 0))
paths.task_done()
continue
# Look for subcategories
try:
for elem in soup.find_all('div', class_ = 'CategoryTreeItem'):
elem = nextn(elem.children, 2)
add(elem)
except Exception as e:
warnings.warn("Unexpected exception occured when trying to parse subcategories from page: " + str(e), UserWarning)
fails.append((path, 1))
# Look for next page of subcategories (may or may not exist)
try:
elem = soup.find('a', href = True, text = 'next page')
add(elem)
except Exception as e:
warnings.warn("Unexpected exception occured when trying to search for next page of subcategories: " + str(e), UserWarning)
fails.append((path, 2))
# Look for image links
try:
for elem in soup.find_all('li', class_ = 'gallerybox'):
elem = next(next(next(nextn(elem.children, 1).children).children).children)
if elem.name == 'img':
src = elem['src']
if not src is None:
ext = src[src.rindex('.') + 1:].lower()
if ext in extensions:
alt = elem['alt']
if alt is None:
alt = ''
found.add((src, alt))
except Exception as e:
warnings.warn("Unexpected exception occured when trying to parse image URLs from page: " + str(e), UserWarning)
fails.append((path, 3))
paths.task_done()
hrefs = set()
paths = Queue()
found = set()
fails = []
chunk = 64
total = 0
outdir = input('Enter output directory path: ')
os.makedirs(outdir, exist_ok = True)
outfp = os.path.join(outdir, 'output.txt')
ooffp = os.path.join(outdir, 'failed.txt')
threads = []
for i in range(8):
thread = Thread(target = worker, daemon = True)
thread.start()
threads.append(thread)
paths.put('/wiki/Category:Topics')
data = []
while found or fails or any(thread.is_alive() for thread in threads):
if found:
data.append(found.pop())
if len(data) == chunk:
total += chunk
logging.info('Found %d images' % total)
with open(outfp, 'a') as f:
for src, alt in data:
f.write(src + '\t' + alt + '\n')
data.clear()
if fails:
with open(ooffp, 'a') as f:
path, code = fails.pop()
f.write(path + '\t' + str(code) + '\n')
total += len(data)
with open(outfp, 'a') as f:
for src, alt in data:
f.write(src + '\t' + alt + '\n')
logging.info('Finished with %d images' % total)