【发布时间】:2011-12-16 14:57:07
【问题描述】:
我在这里浏览了几篇文章,但我无法理解使用 Python 从给定 URL 批量下载图像和文本。
import urllib,urllib2
import urlparse
from BeautifulSoup import BeautifulSoup
import os, sys
def getAllImages(url):
query = urllib2.Request(url)
user_agent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)"
query.add_header("User-Agent", user_agent)
page = BeautifulSoup(urllib2.urlopen(query))
for div in page.findAll("div", {"class": "thumbnail"}):
print "found thumbnail"
for img in div.findAll("img"):
print "found image"
src = img["src"]
if src:
src = absolutize(src, pageurl)
f = open(src,'wb')
f.write(urllib.urlopen(src).read())
f.close()
for h5 in div.findAll("h5"):
print "found Headline"
value = (h5.contents[0])
print >> headlines.txt, value
def main():
getAllImages("http://www.nytimes.com/")
上面现在是一些更新的代码。发生什么,什么都不是。代码没有找到任何带有缩略图的 div,显然,没有任何打印结果....所以我可能错过了一些指向包含图像和标题的正确 div 的指针?
非常感谢!
【问题讨论】:
-
如果您能解释在尝试下载文件时遇到的确切问题,您可能会得到更详细的答案。你读过像stackoverflow.com/questions/3042757/… 这样的帖子吗,其中包含在他们的答案中下载图片的代码?
标签: python beautifulsoup urllib2 urllib