Python BeautifulSoup web映像爬虫IOError:[Errno 2]没有这样的文件或目录
我编写了以下Python代码来抓取网站www.style.com上的图像Python BeautifulSoup web映像爬虫IOError:[Errno 2]没有这样的文件或目录,python,python-2.7,beautifulsoup,web-crawler,Python,Python 2.7,Beautifulsoup,Web Crawler,我编写了以下Python代码来抓取网站www.style.com上的图像 import urllib2, urllib, random, threading from bs4 import BeautifulSoup import sys reload(sys) sys.setdefaultencoding('utf-8') class Images(threading.Thread): def __init__(self, lock, src): threadin
import urllib2, urllib, random, threading
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Images(threading.Thread):
def __init__(self, lock, src):
threading.Thread.__init__(self)
self.src = src
self.lock = lock
def run(self):
self.lock.acquire()
urllib.urlretrieve(self.src,'./img/'+str(random.choice(range(9999))))
print self.src+'get'
self.lock.release()
def imgGreb():
lock = threading.Lock()
site_url = "http://www.style.com"
html = urllib2.urlopen(site_url).read()
soup = BeautifulSoup(html)
img=soup.findAll(['img'])
for i in img:
print i.get('src')
Images(lock, i.get('src')).start()
if __name__ == '__main__':
imgGreb()
但我有一个错误:
IOError:[Errno 2]没有这样的文件或目录:'/images/homepage-2013-十月/header/logo.png'
怎么解决呢?
这还能递归地找到网站中的所有图像吗?我指的是主页上没有的其他图片
谢谢
javascript:void(0)代码>,您将永远无法获取该页面。我添加了try except
,以避免该错误。或者,您可以智能地检测URL是否以jpg/gif/png
结尾。我会把这件事告诉你:)
urllib
和beautifulsou
来做任何事情。如果你真的想挑战自己,也许你可以尝试学习,这是一个更强大的工具李>
直接尝试下面的代码:
import urllib2
from bs4 import BeautifulSoup
import sys
from urllib import urlretrieve
reload(sys)
def imgGreb():
site_url = "http://www.style.com"
html = urllib2.urlopen(site_url).read()
soup = BeautifulSoup(html)
img=soup.findAll(['img'])
for i in img:
try:
# built the complete URL using the domain and relative url you scraped
url = site_url + i.get('src')
# get the file name
name = "result_" + url.split('/')[-1]
# detect if that is a type of pictures you want
type = name.split('.')[-1]
if type in ['jpg', 'png', 'gif']:
# if so, retrieve the pictures
urlretrieve(url, name)
except:
pass
if __name__ == '__main__':
imgGreb()
您提到的错误不在代码中。您应该发布pythonit给出的完整回溯错误,该错误将生成错误:InvalidURL:非数字端口:“void(0);”@randomp我暂时删除了OOP部分,因为它在开始时很混乱。也许你可以试试看这些代码是否有效。如果是这样,您可以使用OOP重新实现。@randomp它对您有用吗?如果是,请将此问题标记为已回答,这将有助于其他人