从匹配BeautifulGroup中特定模式的页面中提取所有URL

2024-04-20 13:06:43 发布

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

我用beauthoulsoup来解析一个HTML页面。我需要从一个页面中提取匹配特定regex模式的所有url和句子。E、 g

http.*?example\.php

我该怎么做?在


Tags: httpurlexamplehtml模式页面regex句子
1条回答
网友
1楼 · 发布于 2024-04-20 13:06:43

由于您不关心url在何处,无论是在标记中还是在句子中,您只需在现有的原始html上运行re.findall()。当然,你得做得比那些微不足道的正则表达式做得更好。请看:

(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*

(来自http://regexlib.com/Search.aspx?k=URL,始终是正则表达式配方的好资源)。在

下面是一些代码:

^{pr2}$

更新:Beefier regex。在

更新:如果要迭代匹配项,可以使用re.finditer

for match in re.finditer(r"(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*", html):
    print match.group()

相关问题 更多 >