gpt4 book ai didi

python - BeautifulSoup:如何选择特定标签

转载 作者:太空狗 更新时间:2023-10-30 02:21:29 25 4
gpt4 key购买 nike

当你想捕获一个标签的 child 时,我对美丽汤的工作原理感到困惑。所以,我有以下 HTML 代码

<div class="media item avatar profile">
<a href="http://..." class="media-link action-medialink">
<img class="media-item-img" src="http://...jpeg" alt="name" title="name" width="150" height="200">
</a>
</div>

我想抓取 src 标签。我正在使用以下代码:

soup = BeautifulSoup(file_)
for x in soup.find('div', attrs={'class':'media item avatar profile'}).findNext('img'):
print x

这将打印整个 img 标签。我如何只选择 src ?

谢谢。

最佳答案

src 是一个 attribute of the tag .获得标签后,像访问字典键一样访问属性;您只找到了 a 标签,因此您还需要导航到包含的 img 标签:

for x in soup.find_all('div', attrs={'class':'media item avatar profile'}):
print x.a.img['src']

您的代码使用了返回 tag 对象的 findNext();循环给你 child ,所以 ximg 对象。我将其更改为更直接和更清晰。 x 现在是 div,我们直接导航到第一个 a 并包含 img 标签。

关于python - BeautifulSoup:如何选择特定标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15920039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com