在Python中从URL中提取GIF图像(仅返回字符串?)

时间:2015-11-11 09:36:49

标签: python url gif

首先,有很多关于从URL中提取GIF的相关问题,但是大多数问题都与Python的语言不同。其次,谷歌搜索提供了许多如何使用请求和解析器(如lxml或beautifulsoup)执行此操作的示例。但是,我认为我的问题特定于此网址,而且我无法弄清楚为什么相关图片没有附加特定网址(http://cactus.nci.nih.gov/chemical/structure/3-Methylamino-1-%28thien-2-yl%29-propane-1-ol/image

这就是我试过的

molecule_name = "3-Methylamino-1-(thien-2-yl)-propane-1-ol"
molecule = urllib.pathname2url(molecule_name)
response = requests.get("http://cactus.nci.nih.gov/chemical/structure/"+ molecule+"/image")
response.encoding = 'ISO-8859-1'
print type(response.content)

我刚拿回一个说GIF87au的字符串。我知道这与GIF在二进制等方面有关。但我不知道如何使用脚本在该特定页面中下载该GIF文件。

此外,如果我设法下载GIF文件,例如,最好使用哪些模块来制作最后一列中嵌入了GIF文件的表(csv或excel样式)?

1 个答案:

答案 0 :(得分:1)

据我所知,你的代码对我有用。

molecule_name = "3-Methylamino-1-(thien-2-yl)-propane-1-ol"
molecule = urllib.pathname2url(molecule_name)
response = requests.get("http://cactus.nci.nih.gov/chemical/structure/"+molecule+"/image")
response.encoding = 'ISO-8859-1'
print len(response.content)

输出“1080”。

至于手头的第二项任务......把它放到文件中。我会像这样使用xlsxwriter:

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('molecules.xlsx')
worksheet = workbook.add_worksheet()

# Input data
worksheet.write(0, 0, "My molecule") # A1 == 0, 0
worksheet.insert_image('B1', 'molecule1234.png')

workbook.close()

请参阅http://xlsxwriter.readthedocs.org/index.html

你必须将.gif转换为.png,因为截至目前xlsxwriter不支持gifs(正如jmcnamara指出的那样)。在这里,您可以了解如何使用PIL进行操作 - How to change gif file to png file using python pil

您可以使用多种方法显示gif。我只是将它保存到文件并使用其他一些软件。如果您想以编程方式查看它们,可以使用例如Play Animations in GIF with Tkinter中使用的Tkinter。