python - 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,\&]$)')
有一个更好的方法吗?
解决方案
这是您要查找的正则表达式:
https?://www.mywebsite.com\S*$
你的正则表达式有什么问题?
([http,https]://www.mywebsite.com\S[\.html,\.php,\&]$)
- 两边的牙套都没用
[]
表示这些字符中的任何一个,因此在 中[http,https]
,您正在寻找一个字符,可能是“h
”、“t
”、“t
”、“p
”、“s
”或“,
”\S
只捕获一个字符,您需要在它之后添加一个乘数- 这
[\.html,\.php,\&]
部分也是一样的
推荐阅读
- javascript - 循环遍历 Object.keys 时,我的 ArrayList 显示为空
- laravel - 我应该如何设置删除订阅的架构?
- python-3.x - 无法在位置 0 解析字符串“19961101-11:00”
- json - 如何从 VUE 中的另一个 API 加载额外的 JSON 数据?
- google-sheets-api - 在 c# 中使用 googlesheets api v4 获取命名范围列表
- python - 定义关于“自我”的类变量
- python-3.x - 如何在另一个云函数中调用云函数并使用 python 传递一些输入参数或参数?
- node.js - 使用 Nodejs 控制台应用程序未显示表数据
- python - 如何使用 Python 检查 Excel 工作表的值?
- javascript - Javascript删除字符串中目录的结尾