我有一些具有以下结构的 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&groups=oscar_winner,oscar_nominee&gender=male&count=100&start=101&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/