【问题标题】:Matching url in HTML using regex使用正则表达式匹配 HTML 中的 url
【发布时间】:2017-01-19 03:45:53
【问题描述】:

我已经有一段时间没有使用正则表达式了,我觉得这应该很容易理解。

我有一个充满链接的网页,看起来像下面代码中的 string_to_match。我只想获取链接中的数字,例如 string_to_match 中的数字“58”。对于我的生活,我无法弄清楚。

import re
string_to_match = '<a href="/ncf/teams/roster?teamId=58">Roster</a>'
re.findall('<a href="/ncf/teams/roster?teamId=(/d+)">Roster</a>',string_to_match)

【问题讨论】:

标签: python regex


【解决方案1】:

您可以结合使用 HTML 解析(使用 BeautifulSoup 解析器)来定位所需的链接并提取 href 属性值和 URL 解析,而不是使用正则表达式,在这种情况下,我们将使用正则表达式:

import re
from bs4 import BeautifulSoup

data = """
<body>
    <a href="/ncf/teams/roster?teamId=58">Roster</a>
</body>
"""

soup = BeautifulSoup(data, "html.parser")
link = soup.find("a", text="Roster")["href"]

print(re.search(r"teamId=(\d+)", link).group(1))

打印58

【讨论】:

    【解决方案2】:

    我建议使用BeautifulSouplxml,值得学习曲线。

    ...但是如果你还想使用正则表达式

    re.findall('href="[^"]*teamId=(\d+)',string_to_match)
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多