[英]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>
'''
according to picture I attached, I want to extract all "kt-post-card__body" attrs and then from each one of them, extract:根据我附上的图片,我想提取所有“kt-post-card__body”属性,然后从它们中提取:
("kt-post-card__title", "kt-post-card__description")
like a list.像一个列表。
I tried this:我试过这个:
ads = soup.find_all('div',{'class':'kt-post-card__body'})
but with ads[0].div
I only access to "kt-post-card__title"
while "kt-post-card__body"
has three other sub tags like: "kt-post-card__description"
and "kt-post-card__bottom"
... , why is that?但是使用
ads[0].div
我只能访问"kt-post-card__title"
,而"kt-post-card__body"
还有其他三个子标签,例如: "kt-post-card__description"
和"kt-post-card__bottom"
。 .. , 这是为什么?
Try this:尝试这个:
ads = soup.find_all('div',{'class':'kt-post-card__body'})
ads[0]
I think you're getting only the first div because you called ads[0].div
我认为你只得到第一个 div 因为你调用
ads[0].div
Cause your question is not that clear - To extract the classes:因为你的问题不是很清楚 - 提取类:
for e in soup.select('.kt-post-card__body'):
print([c for t in e.find_all() for c in t.get('class')])
Output:输出:
['kt-post-card__title', 'kt-post-card__description', 'kt-post-card__bottom', 'kt-post-card__bottom-description', 'kt-text-truncate']
To get the texts you also have to iterate your ResultSet
and could access each elements text to fill your list or use stripped_strings
.要获取文本,您还必须迭代您的
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)
Output:输出:
['Example_1', 'Example_2']
or或者
print(list(e.stripped_strings))
Output:输出:
['Example_1', 'Example_2', 'Example_4']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.