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



首先,关于从URL中提取GIF,有很多相关的问题,但大多数问题的语言与Python不同。其次,谷歌搜索提供了许多使用请求和解析器(如lxml或beautifulsoup)来实现这一点的示例。然而,我认为我的问题是特定于这个URL的,我不太明白为什么有问题的图像没有附加特定的URL(http://cactus.nci.nih.gov/chemical/structure/3-Methylamino-1-%28thien-2-基%29-丙-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 type(response.content)

我只得到一个字符串,上面写着GIF87au。我知道这与GIF是二进制的等有关,但我不太清楚如何使用脚本将GIF文件加载到特定页面中。

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

据我所知,您的代码对我有效。

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不支持gif(正如jmcnamara所指出的)。在这里你可以看到如何使用PIL做到这一点-如何使用python-PIL将gif文件更改为png文件。

可以使用多种方法显示gif。我会把它保存到文件中,然后用一些其他软件。如果你想以编程方式查看它们,你可以使用例如这里使用的Tkinter用Tkinter播放GIF中的动画。

最新更新