python - python中的正则表达式帮助查找链接
问题描述
我正在解析 html 页面中的一些链接,并且我想检测与以下模式匹配的所有链接:
http://www.example.com/category1/some-content-here/
http://www.example.com/category-12/some-content-here/
它不应与以下链接匹配:
http://www.example.com/category1/
http://www.example.org/category-12/some-content-here/
谢谢!
解决方案
您可以使用BeautifulSoup
解析 HTMLa
标记,然后使用正则表达式过滤原始的完整结果:
from bs4 import BeautifulSoup as soup
import re
sample = """
<div id='test'>
<a href='http://www.example.com/category1/some-content-here/'>Someting</a>
<a href='http://www.example.com/category-12/some-content-here/'>Someting Here</a>
<a href='http://www.example.com/category1/'>Someting1</a>
<a href='http://www.example.org/category-12/some-content-here/'>Sometingelse</a>
</div>
"""
a = [i['href'] for i in soup(sample, 'lxml').find_all('a') if re.findall('http://[\w\.]+\.com/[\w\-]+/[\w\-]+/', i['href'])]
输出:
['http://www.example.com/category1/some-content-here/', 'http://www.example.com/category-12/some-content-here/']
推荐阅读
- python - Python读取播放声音数据
- charts - 谷歌饼图图例标有线条颜色
- javascript - 你如何在 React 字符串中添加换行符?
- sql - 使用相同的数字数组使用 Op.or 和 Op.ne 进行 Sequelize 查询
- php - 我可以使用 Vue-CLI 构建应用程序,然后将其包含在当前的 PHP 应用程序中吗?
- docker - 即使在 docker 容器中安装 npm 后,node_modules 也会丢失
- azure - ValidationTechnicalProfile 何时执行?
- android - 在 AOSP 中完成整个构建后如何运行命令?
- javascript - 如何在这个简单的图表中正确格式化 x 标签?
- c - 为什么这个while循环没有结束?