加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
xkcd_downloader.py 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
Jérôme Krell 提交于 2019-10-10 14:22 . Reformat Code by PyCharm-Community
"""
Written by: Shreyas Daniel - github.com/shreydan
Written on: 26 April 2017
Description: Download latest XKCD Comic with this program.
NOTE:
if this script is launched from the cloned repo, a new folder is created.
Please move the file to another directory to avoid messing with the folder structure.
"""
import os
import urllib.request
import requests
from lxml import html
def main():
# opens xkcd.com
try:
page = requests.get("https://www.xkcd.com")
except requests.exceptions.RequestException as e:
print(e)
exit()
# parses xkcd.com page
tree = html.fromstring(page.content)
# finds image src url
image_src = tree.xpath(".//*[@id='comic']/img/@src")[0]
image_src = "https:" + str(image_src)
# gets comic name from the image src url
comic_name = image_src.split('/')[-1]
# save location of comic
comic_location = os.getcwd() + '/comics/'
# checks if save location exists else creates
if not os.path.exists(comic_location):
os.makedirs(comic_location)
# creates final comic location including name of the comic
comic_location = comic_location + comic_name
# downloads the comic
urllib.request.urlretrieve(image_src, comic_location)
if __name__ == "__main__":
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化