【问题标题】:Extract href from <a> tag with class uses Regex从带有类的 <a> 标记中提取 href 使用正则表达式
【发布时间】:2018-07-18 01:31:21
【问题描述】:

我需要从网站上读取许多页面并使用正则表达式提取所有具有“活动”类的链接。 此标记可以在 HREF 值之前或之后具有类 attr。

我的代码是:

    try:
        p = requests.get(url, timeout=4.0)
    except:
        p = None
    if p and p.content and p.status_code < 400:
        canonical_url = re.search('<a class="active" href="(.*)?"', p.content, flags=re.MULTILINE|re.IGNORECASE|re.DOTALL|re.UNICODE)

但是使用这个正则表达式,我只能在 HREF 之前而不是之后捕获类活动的链接。 谢谢。

【问题讨论】:

标签: python regex href


【解决方案1】:

鉴于 OP 在问题下方的 cmets 中指定了以下内容,可以使用正则表达式。不过要小心,因为在尝试解析 HTML 时,正则表达式很容易 break

我使用的是 BS4,但我的老板让我使用正则表达式,因为 BS4 提取简单链接有点过头了

See regex in use here

<a\b(?=[^>]* class="[^"]*(?<=[" ])active[" ])(?=[^>]* href="([^"]*))
  • &lt;a 按字面意思匹配
  • \b 将位置断言为单词边界
  • (?=[^&gt;]* class="[^"]*(?&lt;=[" ])active[" ]) 正向前瞻确保以下匹配。
    • [^&gt;]* 匹配除&gt; 之外的任何字符任意次数
    • class=" 逐字匹配
    • [^"]* 匹配除" 以外的任何字符任意次数
    • (?&lt;=[" ]) 正向向后看,确保前面是集合中的字符
    • active 从字面上匹配这个
    • [" ]匹配集合中的任一字符
  • (?=[^&gt;]* href="([^"]*)) 积极的前瞻确保接下来的匹配
    • [^&gt;]* 匹配除&gt; 之外的任意字符任意次数
    • href=" 从字面上匹配
    • ([^"]*) 将除" 之外的任何字符任意次数捕获到捕获组 1 中

给定以下示例,仅匹配前 3 个:

<a class="active" href="something">
<a href="something" class="active">
<a href="something" class="another-class active some-other-class">

<a class="inactive" href="something">
<a not-class="active" href="something">
<a class="active" not-href="something">

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2022-01-05
  • 2016-01-19
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多