[英]extract tags from soup with BeautifulSoup
'''
<div class="kt-post-card__body>
<div class="kt-post-card__title">Example_1</div>
<div class="kt-post-card__description">Example_2</div>
<div class="kt-post-card__bottom">
<span class="kt-post-card__bottom-description kt-text-truncate" title="Example_3">Example_4</span>
</div>
</div>
'''
根据我附上的图片,我想提取所有“kt-post-card__body”属性,然后从它们中提取:
("kt-post-card__title", "kt-post-card__description")
像一个列表。
我试过这个:
ads = soup.find_all('div',{'class':'kt-post-card__body'})
但是使用ads[0].div
我只能访问"kt-post-card__title"
,而"kt-post-card__body"
还有其他三个子标签,例如: "kt-post-card__description"
和"kt-post-card__bottom"
。 .. , 这是为什么?
尝试这个:
ads = soup.find_all('div',{'class':'kt-post-card__body'})
ads[0]
我认为你只得到第一个 div 因为你调用ads[0].div
因为你的问题不是很清楚 - 提取类:
for e in soup.select('.kt-post-card__body'):
print([c for t in e.find_all() for c in t.get('class')])
输出:
['kt-post-card__title', 'kt-post-card__description', 'kt-post-card__bottom', 'kt-post-card__bottom-description', 'kt-text-truncate']
要获取文本,您还必须迭代您的ResultSet
并可以访问每个元素文本以填充您的列表或使用stripped_strings
。
from bs4 import BeautifulSoup
html_doc='''
<div class="kt-post-card__body">
<div class="kt-post-card__title">Example_1</div>
<div class="kt-post-card__description">Example_2</div>
<div class="kt-post-card__bottom">
<span class="kt-post-card__bottom-description kt-text-truncate" title="Example_3">Example_4</span>
</div>
</div>
'''
soup = BeautifulSoup(html_doc)
for e in soup.select('.kt-post-card__body'):
data = [
e.select_one('.kt-post-card__title').text,
e.select_one('.kt-post-card__description').text
]
print(data)
输出:
['Example_1', 'Example_2']
或者
print(list(e.stripped_strings))
输出:
['Example_1', 'Example_2', 'Example_4']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.