如何使用 BeautifulSoup 提取 div 的属性值

how to extract an attribute value of div using BeautifulSoup

我有一个 div,它的 ID 是 "img-cont"

<div class="img-cont-box" id="img-cont" style='background-image: url("http://example.com/example.jpg");'>

我想使用漂亮的 soup.How 提取背景图像中的 url 可以吗?

您可以 find_allfind 进行第一场比赛。

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))