首页 > 解决方案 > Python:正则表达式查找关联的 HTML 链接

问题描述

我需要一些帮助来编写一个可以从网页中找到附属链接的正则表达式模式。

示例代码:

import requests,re
from bs4 import BeautifulSoup
res = requests.get('https://www.example.com')
soup = BeautifulSoup(res.text,'lxml')
links = soup.find_all('a', href=True)

# example_of_affiliate_links = ['http://example.com/click/click?p=1&t=url&s=IDHERE&url=https://www.mywebsite.com/920&f=TXL&name=electronic/ps4/','https://example.net/click/camref:IDhere/destination:https://www.mywebsite.com/product/138/sony-ps4.html']

我想使用以下正则表达式模式收集“mywebsite.com”的所有附属链接,但它没有捕获任何链接。

pattern = re.compile(r'([http,https]://www.mywebsite.com\S[\.html,\.php,\&]$)')

有一个更好的方法吗?

标签: pythonregexweb-scrapingbeautifulsoup

解决方案


这是您要查找的正则表达式:

https?://www.mywebsite.com\S*$

你的正则表达式有什么问题?

([http,https]://www.mywebsite.com\S[\.html,\.php,\&]$)
  • 两边的牙套都没用
  • []表示这些字符中的任何一个,因此在 中[http,https],您正在寻找一个字符,可能是“ h”、“ t”、“ t”、“ p”、“ s”或“ ,
  • \S只捕获一个字符,您需要在它之后添加一个乘数
  • [\.html,\.php,\&]部分也是一样的

推荐阅读