【问题标题】:How can I find a file name in a block of text using python?如何使用 python 在文本块中查找文件名?
【发布时间】:2012-07-26 21:48:02
【问题描述】:

我已经使用 Python 获得了网页的 HTML,现在我想找到在标题中链接到的所有 .CSS 文件。我尝试了分区,如下所示,但在运行时出现错误“IndexError:字符串索引超出范围”并将每个都保存为自己的变量(我知道如何做这部分)。

sytle = src.partition(".css")
style = style[0].partition('<link href=')
print style[2]
c =1

我不认为这是处理这个问题的正确方法,所以希望得到一些建议。提前谢谢了。这是我需要从中提取 .CSS 文件的文本的一部分。

    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />

<!--[if gte IE 7]><!-->
<link href="/stylesheets/master.css?1342791430" media="screen, projection" rel="stylesheet" type="text/css" />

<link href="/stylesheets/adapt.css?1342791413" media="screen, projection" rel="stylesheet" type="text/css" />
<!-- <![endif]-->
<link href="/stylesheets/print.css?1342791421" media="print" rel="stylesheet" type="text/css" />
<link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon-precomposed" />
<link href="http://dribbble.com/shots/popular.rss" rel="alternate" title="RSS" type="application/rss+xml" />

【问题讨论】:

  • 您接受了一个似乎出于某种奇怪原因而获得支持的答案。使用正则表达式来解析 HTML 是丑陋的、容易出错的、容易损坏和不灵活的。您应该使用适当的 HTML 解析器来处理 HTML 数据 [lxml.html、BeautifulSoup 等...) HTML 是结构化数据,它不仅仅是“文本”

标签: python file parsing text


【解决方案1】:

您应该为此使用regular expression。请尝试以下操作:

/href="(.*\.css[^"]*)/g

编辑

import re
matches = re.findall('href="(.*\.css[^"]*)', html)
print(matches)

【讨论】:

  • 知道了!感谢您的快速回复。
  • 我已经扩展了我的答案。这有帮助吗?
  • 是的,非常如此。再次感谢您的帮助。
【解决方案2】:

我的答案与Jon Clements' answer 相同,但我测试了我的答案并添加了一些解释。

您应该使用正则表达式。 You can't parse HTML with a regex。正则表达式答案可能有效,但是使用lxml 编写一个强大的解决方案非常容易。这种方法保证返回所有&lt;link rel="stylesheet"&gt;标签的完整href属性,不返回其他标签。

from lxml import html

def extract_stylesheets(page_content):
    doc = html.fromstring(page_content)                        # Parse
    return doc.xpath('//head/link[@rel="stylesheet"]/@href')   # Search

没有必要检查文件名,因为 xpath 搜索的结果已经知道是样式表链接,并且不能保证文件名无论如何都会有 .css 扩展名。简单的正则表达式只会捕获一个非常特定的形式,但一般的 html 解析器解决方案也会在这种情况下做正确的事情,正则表达式会惨遭失败:

<link REL="stylesheet" hREf = 

     '/stylesheets/print?1342791421'
  media="print"
><!-- link href="/css/stylesheet.css" -->

它还可以轻松扩展为仅选择特定媒体的样式表。

【讨论】:

    【解决方案3】:

    值得(使用 lxml.html)作为解析库。

    未经测试

    import lxml.html
    from urlparse import urlparse
    
    sample_html = """<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
    
    <!--[if gte IE 7]><!-->
    <link href="/stylesheets/master.css?1342791430" media="screen, projection" rel="stylesheet" type="text/css" />
    
    <link href="/stylesheets/adapt.css?1342791413" media="screen, projection" rel="stylesheet" type="text/css" />
    <!-- <![endif]-->
    <link href="/stylesheets/print.css?1342791421" media="print" rel="stylesheet" type="text/css" />
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon-precomposed" />
    <link href="http://dribbble.com/shots/popular.rss" rel="alternate" title="RSS" type="application/rss+xml" />
    """
    
    import lxml.html
    page = lxml.html.fromstring(html)
    link_hrefs = (p.path for p in map(urlparse, page.xpath('//head/link/@href')))
    for href in link_hrefs:
        if href.rsplit(href, 1)[-1].lower() == 'css': # implement smarter error handling here
            pass # do whatever
    

    【讨论】:

      猜你喜欢
      • 2015-03-10
      • 2019-10-02
      • 2016-06-29
      • 1970-01-01
      • 2019-02-27
      • 2017-09-26
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      相关资源
      最近更新 更多