HTML看起来
<p class="rating item-rating">
<picture>
<source srcset="/assets/img/ratings/rating-4_5.svg" type="image/svg+xml"/>
<img src="/assets/img/ratings/rating-4_5.png"/>
</picture>
<span>
260
</span>
</p>
我想要
/assets/img/ratings/rating-4_5.png
我应该如何改进下面的代码呢?
img = soup.findAll('p',attrs={'class':'rating item-rating'})
for i in img:
print(i.picture)
您需要访问img
标记,因为它似乎保存了您想要在src
属性中保存的信息。
from bs4 import BeautifulSoup
s = '''<p class="rating item-rating">
<picture>
<source srcset="/assets/img/ratings/rating-4_5.svg" type="image/svg+xml"/>
<img src="/assets/img/ratings/rating-4_5.png"/>
</picture>
<span>
260
</span>
</p>'''
soup = BeautifulSoup(s, 'html.parser')
for p in soup.select('p.rating'):
print(p.picture.img['src'])
您可以在img
标记中轻松获取src
值,例如:
import requests
from bs4 import BeautifulSoup
r = """<p class="rating item-rating">
<picture>
<source srcset="/assets/img/ratings/rating-4_5.svg" type="image/svg+xml"/>
<img src="/assets/img/ratings/rating-4_5.png"/>
</picture>
<span>
260
</span>
</p>"""
source = BeautifulSoup(r,'html')
img = source.findAll('p',attrs={'class':'rating item-rating'})
for parsing in img:
print(parsing.img['src'])