【问题标题】:Batch downloading text and images from URL with Python / urllib / beautifulsoup?使用 Python / urllib / beautifulsoup 从 URL 批量下载文本和图像?
【发布时间】: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


【解决方案1】:

您使用的操作系统不知道如何写入您在src 中传递的文件路径。确保用于将文件保存到磁盘的名称是操作系统可以实际使用的名称:

src = "abc.com/alpha/beta/charlie.jpg"
with open(src, "wb") as f:
    # IOError - cannot open file abc.com/alpha/beta/charlie.jpg

src = "alpha/beta/charlie.jpg"
os.makedirs(os.path.dirname(src))
with open(src, "wb" as f:
    # Golden - write file here

一切都会开始工作。

一些额外的想法:

  1. 确保标准化保存文件路径(例如os.path.join(some_root_dir, *relative_file_path*)) - 否则您将根据src 将图像写入整个硬盘。
  2. 除非您正在运行某种类型的测试,否则最好在您的 user_agent 字符串中宣传您是机器人并尊重 robots.txt 文件(或者,提供某种联系信息,以便人们可以要求您停止如果他们需要)。

【讨论】:

  • 非常感谢您的快速回复,不幸的是,在更改了那一行之后,我仍然没有得到任何结果。运行代码只会产生任何结果...... :(
  • 回溯(最近一次调用最后一次):文件“test.py”,第 40 行,在 main() 文件“test.py”,第 35 行,主调用 = getAllImages(" nytimes.com/") 文件“test.py”,第 21 行,在 getAllImages f = open(src,'wb') IOError: [Errno 2] No such file or directory: u'i1.nyt.com/images/2011/10/27/us/cain1/cain1-thumbStandard.jpg' ..... is这就是该部分正常化发挥作用的地方!?
  • @user1016690 - 是的,这就是我所说的。您正试图在硬盘驱动器上打开http://i1.nyt.com/images/2011/10/27/us/cain1/cain1-thumbStandard.jpg 的文件......并且操作系统合法地抱怨没有名为http:// 的可写设备。 :-)
  • BeautifulSoup4 处理类似文件的对象就好了。只是说。
  • @Martijn - 轻笑 是的,确实如此。更新以解决问题的实际原因。感谢您帮助改进答案!
猜你喜欢
  • 2018-08-03
  • 2019-10-25
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2021-03-31
  • 2021-10-22
相关资源
最近更新 更多