python - 从与 BeautifulSoup 中的特定模式匹配的页面中提取所有 URL

标签 python beautifulsoup

我正在使用 BeautifulSoup 来解析 HTML 页面。我需要从页面中提取与特定正则表达式模式匹配的所有 URL 和句子。例如

http.*?example\.php

我该怎么做?

最佳答案

由于您不关心 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 ,始终是正则表达式配方的良好资源)。

现在一些代码:

matches = re.findall(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)

更新:更强大的正则表达式。

更新:如果您想迭代匹配项,可以使用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()

关于python - 从与 BeautifulSoup 中的特定模式匹配的页面中提取所有 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4694693/

相关文章:

python - 将每个表写入 csv,后跟标题

html - BeautifulSoup html.parser 不理解 img 标签

python - 使用 beautifulsoup 通过 div 标签查找 div 文本

Python 显示图像 - AttributeError

python - 分组后计算数据框中某些值的数量

python - 运行扭曲的应用程序时出错

python - 如何有效地计算字符串中字符频率的前缀和?

python - 在Python中使用BS4抓取数据,嵌套表

string - BeautifulSoup Div 类返回空

python - BeautifulSoup soup.select 切断子标签