【问题标题】:Python. How to parse @font-face in CSS?Python。如何在 CSS 中解析 @font-face?
【发布时间】:2019-12-28 13:05:14
【问题描述】:

如何使用 Python 和 BeautifulSoup(或 lxml / XPath,或其他方式)从(url)中提取字体名称“Open Sans”和两个链接?

<style>
...

    @font-face {
        font-family: "Open Sans";
        src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
             url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
    }

...
</style>

提前感谢您的帮助!

【问题讨论】:

  • BeautifulSoup 不解析 CSS - 它是 HTML/XML 解析器。但是您可以使用re 模块来获取数据。
  • regex101.com/r/mqG8IZ/1 - 也许吧。

标签: css regex python-3.x parsing beautifulsoup


【解决方案1】:
^\s*font-family:\s*"(.*)";$|^.*\surl\("(.*?)"\).*$
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^\s*font-family:\s*\"(.*)\";$|^.*\surl\(\"(.*?)\"\).*$"

test_str = ("<style>\n"
    "...\n\n"
    "    @font-face {\n"
    "        font-family: \"Open Sans\";\n"
    "        src: url(\"/fonts/OpenSans-Regular-webfont.woff2\") format(\"woff2\"),\n"
    "             url(\"/fonts/OpenSans-Regular-webfont.woff\") format(\"woff\");\n"
    "    }\n\n"
    "...\n"
    "</style>")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

here

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2013-02-05
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 2014-05-09
    • 2011-11-16
    相关资源
    最近更新 更多