提问者:小点点

BeautifulSoup从Python中的P类picture标记获取图像名称


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)

共2个答案

匿名用户

您需要访问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'])