【问题标题】:Python: Regex to find associated HTML linksPython:正则表达式查找关联的 HTML 链接
【发布时间】:2020-07-27 02:53:50
【问题描述】:

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

示例代码:

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,\&]$)')

有没有更好的方法来做到这一点?

【问题讨论】:

标签: python regex web-scraping beautifulsoup


【解决方案1】:

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

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

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

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

【讨论】:

  • 这在 example.com/click/… 上失败
  • 如果在 .html 之后放置任何参数,例如 https://example.net/click/camref:IDhere/destination:https://www.mywebsite.com/product/138/sony-ps4.html&q=ps4,则会失败
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 2013-05-31
  • 2013-05-13
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多