python - 找到 html 元素 bs4 子元素的最快方法

标签 python html parsing web-scraping beautifulsoup

我有一些具有以下结构的 HTML:

<div class="article">
    <h1 class="header">Birth Date between 1919-01-01 and 2019-01-01, Oscar-Winning, Oscar-Nominated, Males (Sorted by Popularity Ascending) </h1>
    <br class="clear"/>
    <div class="desc">
        <span>1-100 of 716 names.</span> // I WANT THIS ELEMENT
        <span class="ghost">|</span> <a class="lister-page-next next-page" href="/search/name?birth_date=1919-01-01,2019-01-01&amp;groups=oscar_winner,oscar_nominee&amp;gender=male&amp;count=100&amp;start=101&amp;ref_=rlm">Next »</a>
    </div>
    <br class="clear"/>
</div>

现在我正尝试使用 bs4 从这个 html 中获取特定元素。我尝试这样做:

webSoup = BeautifulSoup(html, 'html.parser')
nextUrl = webSoup.findChildren()[2][0]

但这给了我以下错误:

return self.attrs[key] KeyError: 0

所以,总结一下我的问题:
我如何从带有 bs4 的 html 文档中获取特定索引处的特定子项?

最佳答案

如果你想要第一个匹配类 desc 的跨度,那么你可以使用 css child combinator将父类与子元素标记配对:

webSoup.select_one('.desc > span')

你也可以选择指定parent必须是一个div

div.desc > span

如果有多个匹配项,则使用 webSoup.select 然后索引到返回的列表中。


您可以使用:

nextUrl = webSoup.findChildren()[3].findChildren()[0]
print(nextUrl)

关于python - 找到 html 元素 bs4 子元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593897/

相关文章:

java - 进程 'command ' C :\Program Files\Java\jdk1. 8.0_25\bin\java.exe'' 以非零退出值 2 完成

python - PJSUA --null-audio 用于 python 绑定(bind)

python - 在 python 中使用 *args 和默认参数

python - 使用 numpy 和 pyfits 在 Python 中缩小图像数组的更快方法

python - 单用户应用程序可以使用 Django 开发服务器吗?

javascript - 文本字段到隐藏字段值 - 未设置值

html - CSS未显示在HTML中

algorithm - 解析带有转义符或定界符的嵌套 block 的最有效算法

Scala:我可以将组合器解析器微调为本地贪婪吗?

html - 框内边距/垂直文本对齐问题