首页 > 解决方案 > 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/

谢谢!

标签: pythonregexpattern-matching

解决方案


您可以使用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/']

推荐阅读