我想在搜索后用任何语言解析url的指定部分,(最好是Javascript,但对Python开放
如何获取url的特定部分并保存?
例如,在songking.com中,获取艺人ID的方法是在网站的搜索栏中搜索艺人名称后,查看url的特定部分。
在下面的例子中,艺人ID是 301329.
https:/www.songkick.comartists301329-赛车
我坚信有一种方法可以用python或jsgiven来解析这部分,因为我有一个csv文件,其中有艺术家的名字。而不是一个一个地搜索所有的艺术家。我想知道我的csv文件列的读写算法,并搜索它和解析的网址和savestore。
这将是非常感激,即使我只能得到一个提示,我可以开始。
非常感谢你总是。
可以使用正则表达式来实现。
下面是一个JavaScript实现的例子
const url = "https://www.songkick.com/artists/301329-rac";
const regex = /https:\/\/www\.songkick\.com\/artists\/(\d+)-.+/;
const match = url.match(regex);
if (match) {
console.log('Artist ID: ' + match[1]);
} else {
console.log('No Artist ID found!');
}
这个正则表达式 /https:\/\/www\.songkick\.com\/artists\/(\d+)-.+/
意味着我们正试图匹配以 https:/www.songkick.comartists前面是一组小数、破折号和一组字母。
match()方法检索将字符串与正则表达式进行匹配的结果。
因此它将返回第一个索引中的整体字符串,然后返回匹配的 (\d+)
第二组索引中的(match[1]
在我们的例子中)。)
如果你不确定协议(http vs https),你可以添加一个 ?
在https之后的regex中。这使得https中的s是可选的。所以regex会变成 /https?:\/\/www\.songkick\.com\/artists\/(\d+)-.+/
.
如果你需要更多的解释,请告诉我。
首先,你可以使用 RegEx 简单.在 python
import re
url = 'https://www.songkick.com/artists/301329-rac'
pattern = '/artists/(\d+)-\w'
match = re.search(pattern, url)
if match:
artist_id = match.group(1)
希望对你有所帮助。