BeautifulSoup从find_all的结果中查找url


url = 'http://www.xxx'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
s1 = soup.find_all(id="contents")
print(s1, "n")

find_all:的输出

[<div id="contents" style="width:1000px;padding:10px 0;overflow:hidden;"><table style="margin:0;width:1000px;overflow:hidden;" width="980">
<tr><td style="text-align:center;">
<img src="http://xxx/shop/data/editor/2020090302-01.jpg"/></td></tr></table>
</div>] 

如何从结果中获得img标记的src
我有办法获得url而不是id="contents"选项吗
我只想要结果中的URL。

您可以在div中获得img的src,如下所示:

from bs4 import BeautifulSoup as bs
import urllib
url = 'http://www.cobaro.co.kr/shop/goods/goods_view.php?goodsno=8719&category=003004'
html = urllib.request.urlopen(url).read()
soup = bs(html, 'html.parser')
divs = soup.find_all(id="contents")
for div in divs:
img_tag = div.find('img')
print(img_tag['src'])
Output:
http://cobaro.co.kr/shop/data/editor/2020090302-01.jpg

最新更新