【问题标题】:How to pull out CSS attributes from inline styles with BeautifulSoup如何使用 BeautifulSoup 从内联样式中提取 CSS 属性
【发布时间】:2012-03-05 11:52:49
【问题描述】:

我有这样的事情:

<img style="background:url(/theRealImage.jpg) no-repate 0 0; height:90px; width:92px;") src="notTheRealImage.jpg"/> 

我正在使用 beautifulsoup 来解析 html。有没有把“背景”css属性中的“url”拉出来?

【问题讨论】:

    标签: python css inline beautifulsoup


    【解决方案1】:

    您有几个选择 - 快速而肮脏或正确的方式。快速而肮脏的方式(如果更改标记很容易破坏)看起来像

    >>> from BeautifulSoup import BeautifulSoup
    >>> import re
    >>> soup = BeautifulSoup('<html><body><img style="background:url(/theRealImage.jpg) no-repate 0 0; height:90px; width:92px;") src="notTheRealImage.jpg"/></body></html>')
    >>> style = soup.find('img')['style']
    >>> urls = re.findall('url\((.*?)\)', style)
    >>> urls
    [u'/theRealImage.jpg']
    

    显然,您必须使用它才能使其与多个 img 标记一起使用。

    正确的方式,因为我觉得建议有人在 CSS 字符串上使用正则表达式 :) 感觉很糟糕,所以使用 CSS 解析器。 cssutils,一个我刚刚在 Google 上找到并在 PyPi 上可用的库,看起来它可以完成这项工作。

    【讨论】:

    • 我包含了糟糕的正则表达式方法,因为我意识到大量的抓取工作是一次性的,但如果这段代码要使用一天以上,它应该使用更好的东西,比如 CSS 解析器.再一次,上面的例子非常容易破解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2020-03-19
    • 2012-01-15
    • 2016-05-28
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多