Python program to download the all XKCD comics

9.a) Write a python program to download the all XKCD comics

import re
import requests
from bs4 import BeautifulSoup
site='https://www.codespeedy.com/'
response=requests.get(site)
soup=BeautifulSoup(response.text,'html.parser')
image_tags=soup.find_all('img')
urls=[img['src'] for img in image_tags]
for url in urls:
    filename=re.search(r'/([\w_-]+[.](jpg|gif|png|jpeg))$',url)
    if not filename:
        print("Regular expresion didn't match with the url:{}".formate(url))
        continue
    with open(filename.group(1),'wb')as f:
        if 'http' not in url:
            url='{}{}'.formate(site,url)
        response=requests.get(url)
        f.write(response.content)
print("Download complete, downloaded images can be found in current directory!")

Leave a Reply

Your email address will not be published. Required fields are marked *