获取imgu上图片的URL

2024-10-01 04:56:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动下载imgur文件的过程,为此,我使用beauthoulsoup来获取链接,不过,老实说,我很不明白为什么这不起作用,根据我的研究,它应该:

    soup = BeautifulSoup("http://imgur.com/ha0WYYQ")
    imageUrl = soup.select('.image a')[0]['href']

上面的代码只返回一个空列表,因此返回一个错误。我试图修改它,但没有用。任何和所有的输入都是感激的。在


Tags: 文件imagecomhttp链接过程select老实
2条回答
<div class="post-image">


                        <a href="//i.imgur.com/ha0WYYQ.jpg" class="zoom">
                                    <img src="//i.imgur.com/ha0WYYQ.jpg" alt="Frank in his bb8 costume" itemprop="contentURL">

            </a>


</div>

这是图像标记,"post-image"是一个单字,不能分开。在

^{pr2}$

选择一个标记的快捷方式:

imageUrl = soup.select_one('.post-image a')['href']

要解析文档,请将其传递到BeautifulGroup构造函数中。您可以传入字符串打开的文件句柄

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"))

soup = BeautifulSoup("<html>data</html>")

你的方法有一些问题:

  • BeautifulSoup不需要url,所以您需要先使用库来获取HTML流;并且
  • 根据我所见,您的选择器似乎无效.post-image a。在
r = urllib.urlopen('http://imgur.com/ha0WYYQ').read()
soup = BeautifulSoup(r,'lxml')
soup.select('.post-image a')[0]['href']

或者更优雅:

^{pr2}$

相关问题 更多 >