我正在编写一个给出http地址的小程序,它会在其中找到并下载图像。我目前的情况是:
import urllib2, html
class HTMLNode(object):
def __init__(self,tag,attr,content,closed=True):
self.tag = tag
self.attr = attr
self.content = content
self.closed = closed
def istext(self):
return self.tag == '_text_'
def tostring(self):
if self.istext():
return self.content
ret = '<'+self.tag
for k, v in self.attr.items():
ret += ' '+k+'="'+v+'"'
ret += '>'
if self.closed:
for c in self.content:
ret += c.tostring()
ret += '</'+self.tag+'>'
return ret
def find_by_tag(self,tag):
ret = []
if self.tag == tag: ret += [self]
if not self.istext():
for c in self.content:
ret += c.find_by_tag(tag)
return ret
def imagegrab(url):
req = urllib2.Request(url)
response = urllib2.urlopen(req)
output = open(url, 'wb')
output.write(response.read())
缺少的链接是找到一种方法来使用HTMLNode类的“find_by_tag”功能,以便程序扫描“”标签并从网站下载图片。有人可以帮我吗?
答案 0 :(得分:2)
其他人已经为你完成了这项工作。具体来说,看看BeautifulSoup,它是Python的HTML解析库。你会做的
soup = bs4.BeautifulSoup(...)
for img in soup("img"):
print img.src
或类似;显然,图书馆比这更强大。
您还可以考虑使用requests,它是urllib系列库的包装器,具有非常简单的API。为此,你会做
soup = bs4.BeautifulSoup(requests.get(url).text)