Regex查找并匹配&amp(两种情况都存在和不存在)并清除i

2024-05-23 20:43:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用regex从网页中提取标题,但是有些标题有&;这导致我的regex不匹配。我对regex完全陌生。另外,在搜索的时候,我遇到了这个堆垛溢出,所以尽管我问了这里的问题。(我通读了regex上所有类似的内容和youtube视频,但没有涉及我的问题,因此我在这里问这个问题)

这是我已经写好的正则表达式

match = re.search(r'<h3 class="font-semibold m-0 t-xs-24">(?P<ASN_CODE>AS\d+(&amp)) (?P<NAME>[\w.\s]+)</h3>', s).groups()

我的代码:

s = """HTML source """
#https://ipinfo.io/AS7018  [This is the webpage i am trying to scrap]

match = re.search(r'<h3 class="font-semibold m-0 t-xs-24">(?P<ASN_CODE>AS\d+) (?P<NAME>[\w.\s]+)</h3>', s)
if match:
    asn_code, name = match.groups()
    print(asn_code)
    print(name)

这甚至与没有&;的标题也不匹配 示例网页: https://ipinfo.io/AS7922https://ipinfo.io/AS7018

预期产量: 美国康卡斯特有线通信有限责任公司 美国AT&T服务公司

我不知道如何改变我的正则部分(?)?=&;amp)以同时匹配&;amp;和不匹配&;amp 非常感谢您的指点。你知道吗


Tags: httpsiore网页标题searchmatchh3
1条回答
网友
1楼 · 发布于 2024-05-23 20:43:00

不要试图用正则表达式解析HTML。使用合适的HTML解析器。下面是一个使用标准库中的BeautifulSoup的例子:

#!/usr/bin/env python3
import bs4
import requests


def main():
    response = requests.get('https://ipinfo.io/AS7018')
    soup = bs4.BeautifulSoup(response.content, 'html.parser')
    asn_code, _, name = soup.h3.text.partition(' ')
    print('ASN code:', asn_code, '  Company name:', name)


if __name__ == '__main__':
    main()

相关问题 更多 >