我想使用相同的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
运行它给了我第一个div
与class="description"
但我想只有div
的第二个class="description"
。
任何想法如何我可以忽略第一个div
,只是刮第二?
附:第一个div
总是有h4
标签,第二个div
只有标签之间的纯文本。
如果你做.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>
使用css-selector
,因为它包含nth-of-type
属性以选择规范的第n个元素。此外,语法更清晰。
description_box = soup.select("div.description:nth-of-type(2)")[0]
您可以在css中使用带有类选择器的类型,并将索引用于返回的集合
print(soup.select('div.description')[1].text)