从样式中提取URL:background-url:有beautifulsoup且没有正则表达式? [英] Extracting url from style: background-url: with beautifulsoup and without regex?

查看:386
本文介绍了从样式中提取URL:background-url:有beautifulsoup且没有正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

<div class="image" style="background-image: url('/uploads/images/players/16113-1399107741.jpeg');"

我想获取url,但是如果不使用正则表达式,我将无法做到这一点.甚至有可能吗?

I want to get the url, however I cannot how to do that without the use of regex. Is it even possible?

到目前为止,我使用正则表达式的解决方案是:

so far my solution with regex is:

url = re.findall('\('(.*?)'\)', soup['style'])[0]

推荐答案

您可以尝试使用 cssutils 软件包.这样的事情应该起作用:

You could try using the cssutils package. Something like this should work:

import cssutils
from bs4 import BeautifulSoup

html = """<div class="image" style="background-image: url('/uploads/images/players/16113-1399107741.jpeg');" />"""
soup = BeautifulSoup(html)
div_style = soup.find('div')['style']
style = cssutils.parseStyle(div_style)
url = style['background-image']

>>> url
u'url(/uploads/images/players/16113-1399107741.jpeg)'
>>> url = url.replace('url(', '').replace(')', '')    # or regex/split/find/slice etc.
>>> url
u'/uploads/images/players/16113-1399107741.jpeg'

尽管您最终将需要解析出实际的URL,但此方法应该对HTML的更改更具弹性.如果您真的不喜欢字符串操作和正则表达式,则可以通过这种回旋方式拉出url:

Although you are ultimately going to need to parse out the actual url this method should be more resilient to changes in the HTML. If you really dislike string manipulation and regex, you can pull the url out in this roundabout way:

sheet = cssutils.css.CSSStyleSheet()
sheet.add("dummy_selector { %s }" % div_style)
url = list(cssutils.getUrls(sheet))[0]
>>> url
u'/uploads/images/players/16113-1399107741.jpeg'

这篇关于从样式中提取URL:background-url:有beautifulsoup且没有正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆