尝试从以","结尾的字符串中获取所有链接



我需要从Genius页面获取艺术家相册的所有链接。所有链接都可以在属性数据预加载数据的第五个标签预加载内容值中找到。此值以str.的形式存储在var字符串中

我尝试提取以"开头的所有链接https://genius.com/albums/'并以'结尾,'但没有成功。当我没有使用$符号结束时,我得到了正确数量的链接,但没有必要的结束部分

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
from urllib.request import Request, urlopen
import re
name = input('Rapper - ')
url = 'https://genius.com/artists/'+name+''
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(url,headers=hdr)
html = urlopen(req)
soup = BeautifulSoup(html, 'html.parser')
hrefs = soup.find_all("preload-content")
string = hrefs[5]['data-preload_data']
result = re.findall('(https://genius.com/albums/'+name+'.,$)', string)
print(result)

您可以使用

re.findall(r'(https://genius.com/albums/' + re.escape(name) + '/[^"'s<>]*?)&quot;,', string)

请参阅regex演示。

详细信息

  • (https://genius.com/albums/' + re.escape(name) + '/[^"'s<>]*?)-第1组:
    • https://genius.com/albums/' + re.escape(name) + '/-文字子字符串
    • [^"'s<>]*?-除"'、空白、<>之外的任何零个或多个字符,尽可能少(由于*?惰性量词(
  • &quot;,-文字字符串

请注意,在正则表达式中使用name时,必须转义所有特殊字符,正则表达式才能在语法上正确,因此使用re.escape(name)

最新更新