使用python的bs4解析数据 div class=item a href=productpconlinecomcnmobilebubugao1091110html title=vivo S15 Pro target=_blank img src=img4pconl
以下是使用Python的bs4解析上述数据的示例代码:
from bs4 import BeautifulSoup
html = '''
<div class="item">
<a href="//product.pconline.com.cn/mobile/bubugao/1091110.html" title="vivo S15 Pro" target="_blank">
<img src="//img4.pconline.com.cn/pconline/images/product/20220519/892445_sn8.jpg" width="180"/>
<p class="sTit">vivo S15 Pro</p>
<p class="time">2022年5月19日</p>
</a>
</div>
<div class="item">
<a href="//product.pconline.com.cn/mobile/bubugao/1519007.html" title="vivo S15e" target="_blank">
<img src="//img4.pconline.com.cn/pconline/images/product/20220419/654203_sn8.png" width="180"/>
<p class="sTit">vivo S15e</p>
<p class="time">2022年4月25日</p>
</a>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='item')
for item in items:
title = item.find('p', class_='sTit').text.strip()
date = item.find('p', class_='time').text.strip()
link = item.find('a')['href']
print(title, date, link)
输出结果:
vivo S15 Pro 2022年5月19日 //product.pconline.com.cn/mobile/bubugao/1091110.html
vivo S15e 2022年4月25日 //product.pconline.com.cn/mobile/bubugao/1519007.html
在这个示例中,我们首先使用BeautifulSoup解析了一个HTML字符串,并使用find_all方法找到所有div元素,且其class属性为item。然后,对于每个div元素,我们使用find方法分别找到了标题、日期和链接,并使用text属性获取其文本内容或使用['href']获取链接的href属性。最后,我们将这些信息打印出来
原文地址: https://www.cveoy.top/t/topic/fgSu 著作权归作者所有。请勿转载和采集!