【发布时间】:2013-05-21 17:10:33
【问题描述】:
我正在使用 Django 框架开发一个在 Apache 服务器上运行的应用程序。我当前的脚本在本地桌面上运行时运行良好(没有 Django)。该脚本将网站上的所有图像下载到桌面上的文件夹中。但是,当我在服务器上运行脚本时,一个文件对象只是由 Django 创建的,其中显然有一些东西(应该是谷歌的徽标),但是,我无法打开该文件。我还创建了一个 html 文件,更新了图像链接位置,但是 html 文件创建得很好,我假设因为它都是文本,也许?我相信我可能不得不在某处使用文件包装器,但我不确定。任何帮助表示赞赏,下面是我的代码,谢谢!
from django.http import HttpResponse
from bs4 import BeautifulSoup as bsoup
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
import zipfile
from django.core.servers.basehttp import FileWrapper
def getdata(request):
out = 'C:\Users\user\Desktop\images'
if request.GET.get('q'):
#url = str(request.GET['q'])
url = "http://google.com"
soup = bsoup(urlopen(url))
parsedURL = list(urlparse.urlparse(url))
for image in soup.findAll("img"):
print "Old Image Path: %(src)s" % image
#Get file name
filename = image["src"].split("/")[-1]
#Get full path name if url has to be parsed
parsedURL[2] = image["src"]
image["src"] = '%s\%s' % (out,filename)
print 'New Path: %s' % image["src"]
# print image
outpath = os.path.join(out, filename)
#retrieve images
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlparse.urlunparse(parsedURL), out) #Constructs URL from tuple (parsedURL)
#Create HTML File and writes to it to check output (stored in same directory).
html = soup.prettify("utf-8")
with open("output.html", "wb") as file:
file.write(html)
else:
url = 'You submitted nothing!'
return HttpResponse(url)
【问题讨论】:
-
附加说明分享可能有帮助:在文件的属性下,windows 列出了属性 A,这意味着 windows 将其识别为据我了解的存档文件。
-
这里涉及多个因素。一方面,我不确定谷歌是否会提供标准页面。 Google 可能会为不同的用户代理提供不同的服务。你还说这些是存档的,我不确定,但你应该看到内容标题,你可能能够找到编码,它应该是 gzip 或其他东西
-
我只使用了 google,因为它在页面上只包含一个要解析的图像。我尝试使用 7-zip 打开文件,但收到一条错误消息,提示无法将文件作为存档打开。
-
我并不是真正的 Windows 专家,但您可以通过查看文件头来检查它是什么类型的文件。在 linux libmagic 上可以做到这一点。您可以查看github.com/ahupp/python-magic
-
如果我在 Notepad++ 中查看文件,第一行是 %PNG,这似乎是正确的,因为 google 徽标是 png 文件。但是,当我使用 Django 将图像下载到本地桌面时,Windows 无法识别文件图像文件。如果没有合并 Djano,脚本可以正常工作。
标签: python django apache beautifulsoup