这两天微博有个热搜——你生日那天的宇宙,看上去很有趣,点进去链接发现是 NASA(美国航空航天局) 提供的一个网站(庆祝哈勃望远镜30周年),可以查询一下你生日那天哈勃望远镜拍到的太空图片。但是大概是用的人太多或者国内某些因素,网页加载很慢。因此,小笨聪写了个查询软件供大家体验一下啦。
需要用到的python库有:PyQt5,requests,lxml,openpyxl,pillow,以及一些Python自带的库。先看一下界面 :
具体怎么实现的呢?
1. 首先在网站上可以下载一个 excel 表格,表格大致这样:
里面记录了每个日期哈勃望远镜拍到的宇宙对应的介绍页链接,因此我们需要读取这个表格,
'''导入中的全年数据'''
def loadFullYearData(self, filepath):
full_year_data = {}
excel_data = load_workbook(filepath)
sheet = excel_data.get_sheet_by_name('365')
for idx, row in enumerate(sheet.rows):
if idx > 366: break
if idx > 0: full_year_data[row[0].value.strftime('%Y-%m-%d')[5:]] = row[4].value
return full_year_data
2.然后根据用户输入的日期来获得对应的介绍页链接:
url = self.full_year_data.get(key)
3. 获得介绍页链接之后,通过 requests 库来请求它,并用 xpath 来提取我们需要的数据,即照片链接和照片的介绍,如下图红框所示:
xpath 的路径可以直接在浏览器里 copy,代码实现如下:
res = requests.get(url, headers=headers)
html_root = etree.HTML(res.text)
html = html_root.xpath('//*[@id="main-content"]/section/section/div[1]/div/div/div[2]')[0].xpath('./p')
# 提取介绍
intro = []
for item in html:
intro.append(item.xpath('text()')[0])
# 提取图片链接并下载
idx = -1
while True:
image_url = html_root.xpath('//*[@id="main-content"]/section/section/div[1]/div/div/div[1]/div/a')[idx]
image_url = ('https:' + image_url.xpath('@href')[0]).replace('imgsrc.hubblesite.org/hvi', 'hubblesite.org')
if image_url.split('.')[-1] == 'jpg':
break
idx -= 1
4. 接着,再根据图片链接进行下载就好啦(因为网站的图片加载实在太慢了,所以最好自己设置一下 retry ):
filename = 'tmp.%s' % image_url.split('.')[-1]
f = open(filename, 'wb')
session = requests.Session()
retry = Retry(connect=10000, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
res = session.get(image_url, headers=headers, stream=True, verify=False)
for chunk in res.iter_content(chunk_size=1024): f.write(chunk)
f.close()
5. 最后,利用 PyQt5 再写个简单的可视化界面,把爬虫功能添加上去就行了。另外,大家可以使用 pyinstaller 库将代码打包成 exe 文件方便使用,顺便也练习一下怎么高效使用 pyinstaller 模块。
图片展示:
以上就是此次 Python 制作图片查询小软件的过程,微信公众号“学编程的金融客”后台回复“生日图片”即可获取源码。
微信公众号原文链接
欢迎关注微信公众号:学编程的金融客,作者:小笨聪