我正在尝试搜索网页的源代码,并使用 Python 从中下载各种文件。此脚本在源代码中搜索 .jpg 文件并按预期下载它们。但是,在修改脚本时(将“.jpg”更改为“.png”,如下所示),我收到错误消息:
Traceback (most recent call last):
File "img.py", line 19, in <module> urllib.urlretrieve(images[z], "image"+str(z)+".png")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 91, in urlretrieve
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 237, in retrieve
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 205, in open
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 461, in open_file
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 475, in open_local_file
IOError: [Errno 2] No such file or directory: '/images/adapt-icon-search.png?1342791397'
这是我正在使用的脚本:
import urllib
import urllib2
import re
print "enter url of site (such as 'dribbble.com')"
url = raw_input()
fullurl = "http://"+url
src = urllib2.urlopen(fullurl)
src = src.read()
images = re.findall('src="(.*\.png[^"]*)', src)
z=0
while z < len(images):
urllib.urlretrieve(images[z], "image"+str(z)+".png")
print "done"
z+=1
非常感谢您了解为什么此脚本不适用于 .png 文件。提前谢谢了。
更新:下面是我要搜索的源示例:
<span rel="tipsy" title="This shot has rebounds." class="rebound-mark has-rebounds">1</span>
</a>
</div>
</div>
<h2>
<a href="/Dash" class="url" rel="contact" title="Dash"><img alt="Avatar-new" class="photo fn" src="http://dribbble.s3.amazonaws.com/users/107759/avatars/original/avatar-new.png?1339961321" /> Dash</a>
<a href="/account/pro" class="badge-link">
<span class="badge badge-pro">Pro</span>
</a>
</h2>