这是我尝试过的代码。文件大小为0字节。我还设置了imagedata=br.download(…),它报告len()为0。我已经研究了好几个小时了…什么好主意吗?
pre_record_soup='[<img src='/show_pic.php?id=316600'>]' #simplified
def func_get_pic(pre_record_soup, br=spynner.Browser()):
baseurl='http://www.testsite.com/'
for record in pre_record_soup:
imagetag=record.find('img')
filename = 'image.jpg' #set name of file afterdownload
try:
if imagetag:
piclink = imagetag.find('img')['src']
else:
piclink = 'basicimages/icons/icon.gif'
filename = 'icon.gif'
except TypeError:
return None
print baseurl+piclink #this prints the expected link
print filename #this prints the filename I want
with open('/home/myhome/'+filename, 'wb') as handle:
br.download(baseurl+piclink,handle) #not retrieving image...
我还在spynner的身份验证会话中调用该函数。斯宾纳帮我登录了一个网站,我把这些数据和其他数据都刮了出来。其他数据(文本)擦得很好。此外,当我在浏览器中访问图像URL时,它会正确显示jpeg文件。
谢谢你的帮助!
编辑- 2014年3月10日//这是spynner给我的调试信息。请注意,php提供的图像的url格式是正确的,并且在正确下载的.gif:
中缺少"从下载流中读取"。http://www.testsite.com/show_pic.php?id=81851
Request: GET http://www.testsite.com/show_pic.php?id=81851
Start download: http://www.testsite.com/show_pic.php?id=81851
Download finished: http://www.testsite.com/show_pic.php?id=81851
http://www.testsite.com/basicimages/icons/icon.gif
Request: GET http://www.testsite.com/basicimages/icons/icon.gif
Start download: http://www.testsite.com/basicimages/icons/icon.gif
Read from download stream (419 bytes): http://www.testsite.com/basicimages/icons/icon.gif
Download finished: http://www.testsite.com/basicimages/icons/icon.gif
来自br的附加信息调试流。负载。注意content-length为0字节。这在Firefox中加载得很好…啊!
Page load started
Request: GET http://www.testsite.com/show_pic.php?id=81851
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.21 (KHTML, like Gecko) Qt/4.8.4 Safari/537.21
Reply: 200/OK - http://www.testsite.com/show_pic.php?id=81851
Date: Tue, 11 Mar 2014 01:16:35 GMT
Server: Apache
Set-Cookie: PHPSESSID=abvcv4j6hbu57a638tc8pg8i77b19bl0; path=/
Content-Length: 0
Connection: close
Content-Type: text/html
Page load finished (39 bytes): http://www.testsite.com/show_pic.php?id=81851 (successful)
根据您的代码,解析后您的piclink
有:
http://www.testsite.com/show_pic.php?id=316600
现在你在做baseurl+piclink
,这意味着:
http://www.testsite.com/http://www.testsite.com/show_pic.php?id=316600
现在你知道错误在哪里了。相应地调整url,它将解决您的问题!
答案:
从登录到testsite的相同代码外部调用函数会打开一个不同的浏览器。将func_get_pic的代码复制并粘贴到登录函数中,运行良好。这是变通办法,直到我弄清楚如何通过登录会话从一个函数到另一个。