繁体   English   中英

Python - Regex - 如何在两组字符串之间查找字符串

[英]Python — Regex — How to find a string between two sets of strings

考虑以下:

<div id=hotlinklist>
  <a href="foo1.com">Foo1</a>
  <div id=hotlink>
    <a href="/">Home</a>
  </div>
  <div id=hotlink>
    <a href="/extract">Extract</a>
  </div>
  <div id=hotlink>
    <a href="/sitemap">Sitemap</a>
  </div>
</div>

您如何在python中使用regex取出sitemap行?

<a href="/sitemap">Sitemap</a>

以下内容可用于拉出锚标签。

'/<a(.*?)a>/i'

但是,有多个锚标签。 还有多个热链接,所以我们也不能真正使用它们?

不要使用正则表达式。 使用BeautfulSoup ,一个HTML解析器。

from BeautifulSoup import BeautifulSoup

html = \
"""
<div id=hotlinklist>
  <a href="foo1.com">Foo1</a>
  <div id=hotlink>
    <a href="/">Home</a>
  </div>
  <div id=hotlink>
    <a href="/extract">Extract</a>
  </div>
  <div id=hotlink>
    <a href="/sitemap">Sitemap</a>
  </div>
</div>"""

soup = BeautifulSoup(html)
soup.findAll("div",id="hotlink")[2].a

# <a href="/sitemap">Sitemap</a>

使用正则表达式解析HTML是个坏主意!

想想下面这段html

<a></a > <!-- legal html, but won't pass your regex -->

<a href="/sitemap">Sitemap<!-- proof that a>b iff ab>1 --></a>

还有更多这样的例子。 正则表达式适用于许多内容,但不适用于解析HTML。

你应该考虑使用Beautiful Soup python HTML解析器。

无论如何,使用正则表达式的临时解决方案是

import re

data = """
<div id=hotlinklist>
  <a href="foo1.com">Foo1</a>
  <div id=hotlink>
    <a href="/">Home</a>
  </div>
  <div id=hotlink>
    <a href="/extract">Extract</a>
  </div>
  <div id=hotlink>
    <a href="/sitemap">Sitemap</a>
  </div>
</div>
"""

e = re.compile('<a *[^>]*>.*</a *>')

print e.findall(data)

输出:

>>> e.findall(data)
['<a href="foo1.com">Foo1</a>', '<a href="/">Home</a>', '<a href="/extract">Extract</a>', '<a href="/sitemap">Sitemap</a>']

为了提取标语的内容:

    <a href="/sitemap">Sitemap</a>

......我会用:

    >>> import re
    >>> s = '''
    <div id=hotlinklist>
    <a href="foo1.com">Foo1</a>
      <div id=hotlink>
        <a href="/">Home</a>
      </div>
      <div id=hotlink>
        <a href="/extract">Extract</a>
      </div>
      <div id=hotlink>
        <a href="/sitemap">Sitemap</a>
      </div>
    </div>'''
    >>> m = re.compile(r'<a href="/sitemap">(.*?)</a>').search(s)
    >>> m.group(1)
    'Sitemap'

如果需要解析HTML,请使用BeautifulSouplxml

另外,你真的需要做什么? 找到最后一个链接? 找到第三个链接? 找到指向/ sitemap的链接? 你不清楚这个问题。 您需要对数据什么?

如果你真的必须使用正则表达式,请查看findall

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM