忽略BeautifulSoup中同一个类的两个div中的第一个

问题描述 投票:0回答:3

我想使用相同的divs刮掉一些有2个class="description"的URL,

示例网址的源代码如下:

<!-- Initial HTML here -->

<div class="description">
<h4> Anonymous Title </h4>
<div class="product-description">
<li> Some stuff here </li>
</div>
</div>

<!-- Middle HTML here -->

<div class="description">
Some text here
</div>

<!-- Last HTML here -->

我正在使用BeautifulSoap使用以下脚本来删除它

# imports etc here
description_box = soup.find('div', attrs={'class': 'description'})
description = description_box.text.strip()
print description

运行它给了我第一个divclass="description"但我想只有div的第二个class="description"

任何想法如何我可以忽略第一个div,只是刮第二?

附:第一个div总是有h4标签,第二个div只有标签之间的纯文本。

python web-scraping beautifulsoup
3个回答
2
投票

如果你做.find_all,它将返回列表中的所有内容。然后只需使用索引1选择该列表中的第二项:

html = '''<!-- Initial HTML here -->

<div class="description">
<h4> Anonymous Title </h4>
<div class="product-description">
<li> Some stuff here </li>
</div>
</div>

<!-- Middle HTML here -->

<div class="description">
Some text here
</div>

<!-- Last HTML here -->'''

soup = BeautifulSoup(html, 'html.parser')
divs = soup.find_all('div', {'class':'description'})
div = divs[1]

输出:

print (div)
<div class="description">
Some text here
</div>

0
投票

使用css-selector,因为它包含nth-of-type属性以选择规范的第n个元素。此外,语法更清晰。

description_box = soup.select("div.description:nth-of-type(2)")[0]

0
投票

您可以在css中使用带有类选择器的类型,并将索引用于返回的集合

print(soup.select('div.description')[1].text)
© www.soinside.com 2019 - 2024. All rights reserved.