如何在find_all函数中使用多个参数?

2024-09-28 18:16:01 发布

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

是否可以在一个soup.find_all函数中使用多个参数从某些元素中查找任何特定项?如果我选择soup.select选项,我想知道的流程可以很容易地应用。更具体地说,请看下面的例子:

from bs4 import BeautifulSoup

html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.find_all(class_='browse-movie-bottom')[0].find_all(class_='browse-movie-tags')[0].find_all("a"):
# for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)

一方面,我使用soup.select()解析电影标记,您知道可以这样使用它,以便所有参数都可以放在一个大括号中。在

另一方面,我使用soup.find_all()进行了同样的操作,它需要在三个不同的大括号中使用三个不同的参数。结果是一样的。在

我的问题是:是否可以使用soup.find_all()函数创建任何表达式,该函数将在一个大括号中包含多个参数,就像我对soup.select()所做的那样。如下所示:

这是一个错误的,但它会让你知道我想要什么样的表达方式:

^{pr2}$

但是,有效的搜索结果是:

Logan Lucky 720p
Logan Lucky 1080p

Tags: 函数httpsdiv参数allfindmovieselect
2条回答

您应该使用CSS选择器:

>>> soup.select(".browse-movie-bottom .browse-movie-tags a")
[<a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>, <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>]
>>> [item.text for item in soup.select(".browse-movie-bottom .browse-movie-tags a")]
[u'Logan Lucky 720p', u'Logan Lucky 1080p']

更多信息:https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

除非您不能使用CSS选择器(因为并不是所有的选择器都实现了),否则您应该使用select。否则,使用更乏味的find_all。在

未实现的CSS选择器示例:第n个子级。 selecting second child in beautiful soup with soup.select?

您可以将一个列表传递给class_属性,这样可以保存对find_all的一次调用,但您需要使用"a"再次调用它,而且您可以使用find_all的快捷方式像soup("a")一样调用:

from bs4 import BeautifulSoup
html_element='''
<div class="browse-movie-bottom">
    <a href="https://yts.ag/movie/logan-lucky-2017" class="browse-movie-title">Logan Lucky</a>
    <div class="browse-movie-year">2017</div>
    <div class="browse-movie-tags">
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 720p</a>
        <a href="https://yts.ag/torrent/download" rel="nofollow" title="Logan Lucky">Logan Lucky 1080p</a>
    </div>
</div>
'''
soup = BeautifulSoup(html_element,"lxml")
for item in soup.findAll(class_=['browse-movie-bottom', 'browse-movie-tags'])[1]('a'):
#for item in soup.select(".browse-movie-bottom .browse-movie-tags a"):
    print(item.text)

相关问题 更多 >