-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxkcd_getter.py
71 lines (55 loc) · 1.98 KB
/
xkcd_getter.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
#!/usr/bin/env python3
# dependencies used for this project
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import io
from PIL import Image
import time
from pathlib import Path
from datetime import date
# path to browser driver and folder to store images
PATH = "/home/felipe/Desktop/software/browser/chromedriver_linux64/chromedriver"
download_path = "/home/felipe/Desktop/various/various_pics/daily_xkcd/"
op = webdriver.ChromeOptions()
op.add_argument('headless')
wd = webdriver.Chrome(PATH,options=op)
# function to randomize and retrieve url to comic
def get_xkcd(wd):
url = "https://xkcd.com/"
wd.get(url)
wd.find_element(By.XPATH,".//a[@href='//c.xkcd.com/random/comic/']").click()
image_url = wd.find_element(By.XPATH,".//img[@style='image-orientation:none']").get_attribute("src")
return image_url
# function to download comic and save it to specified folder
def download_image(download_path, url, file_name):
try:
image_content = requests.get(url).content
image_file = io.BytesIO(image_content)
image = Image.open(image_file)
file_path = download_path + file_name
potential_path = Path(file_path)
if potential_path.exists():
print(f'{file_name} already exists')
else:
with open(potential_path,"wb") as f:
image.save(f,"PNG")
print(f'Success saving {file_name}')
image.show(potential_path)
except Exception as e:
print(f'FAILED - {e}')
# function to log into txt file date and filename per comic downloaded
def log(file_name):
with open("/home/felipe/Desktop/personal/personal_software/python/xkcd_getter/log.txt","a") as f:
f.write(f'{file_name}_{date.today()}\n')
f.close()
# main function
def main():
url = get_xkcd(wd)
file_name = url[29:]
print(file_name)
download_image(download_path,url,file_name)
log(file_name)
print("Done")
if __name__ == '__main__':
main()