如何使用BeautifulSoup从内联样式中提取CSS属性

the*_*pot 9 css python inline beautifulsoup

我有这样的事情:

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

我正在使用beautifulsoup来解析HTML.有没有在"背景"css属性中拉出"url"?

Mat*_*ngo 10

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

>>> 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']
Run Code Online (Sandbox Code Playgroud)

显然,你必须使用它来使它与多个img标签一起使用.

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

  • 我包含了糟糕的正则表达式方法,因为我意识到大量的抓取工作是一次性的,但是如果这段代码要活一天以上,它应该使用更好的东西,比如CSS解析器.上面的例子再次非常易碎. (2认同)