[英]how to extract an attribute value of div using BeautifulSoup
我有一个id为“img-cont”的div
<div class="img-cont-box" id="img-cont" style='background-image: url("http://example.com/example.jpg");'>
我想用美丽的汤来提取背景图像中的网址。我该怎么做?
你可以find
find_all
或find
第一场比赛。
import re
soup = BeautifulSoup(html_str)
result = soup.find('div',attrs={'id':'img-cont','style':True})
if result is not None:
url = re.findall('\("(http.*)"\)',result['style']) # return a list.
试试这个:
import re
from bs4 import BeautifulSoup
html = '''\
<div class="img-cont-box" \
id="img-cont" \
style='background-image: url("http://example.com/example.jpg");'>\
'''
soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div', id='img-cont')
print(re.search(r'url\("(.+)"\)', div['style']).group(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.