You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Beautiful Soup精准提取Setlist.fm指定演出链接?

问题:精准提取Setlist.fm上Nightwish的演出Setlist链接

我尝试从页面抓取链接,当前用Beautiful Soup代码能获取目标链接,但同时返回大量无关内容。目标链接示例如下:

  • setlist/nightwish/2022/quarterback-immobilien-arena-leipzig-germany-2bbca8f2.html
  • setlist/nightwish/2022/brose-arena-bamberg-germany-3bf4963.html
  • setlist/nightwish/2022/arena-gliwice-gliwice-poland-3bc9dc7.html

请问能否仅用Beautiful Soup实现精准提取,还是需要配合regex?现有代码如下:

import requests
import bs4

url = 'https://www.setlist.fm/search?query=nightwish'
reqs = requests.get(url)
soup = bs4.BeautifulSoup(reqs.text, 'html.parser')

urls = []
for link in soup.select('a'):
    urls.append(link)
    print(link.get('href'))

解决方案

两种方式都可实现精准提取,具体方案如下:

方法一:仅用Beautiful Soup(推荐)

观察页面结构可知,目标Setlist链接对应的<a>标签带有特定类名(如link-setlist),直接通过CSS选择器定位即可过滤无关链接:

import requests
import bs4

url = 'https://www.setlist.fm/search?query=nightwish'
reqs = requests.get(url)
soup = bs4.BeautifulSoup(reqs.text, 'html.parser')

target_links = []
# 直接定位目标类名的a标签
for link in soup.select('a.link-setlist'):
    href = link.get('href')
    if href:
        target_links.append(href)
        print(href)

若页面结构调整,也可通过父容器层级缩小范围:

# 先定位Setlist条目容器,再提取内部链接
for item in soup.select('div.setlist-list-item'):
    link = item.find('a', href=True)
    if link and 'setlist/nightwish' in link['href']:
        print(link['href'])

方法二:配合正则表达式

如果无法通过HTML结构精准定位,可直接用正则匹配链接格式:

import requests
import bs4
import re

url = 'https://www.setlist.fm/search?query=nightwish'
reqs = requests.get(url)
soup = bs4.BeautifulSoup(reqs.text, 'html.parser')

# 匹配目标链接格式的正则
pattern = re.compile(r'^/setlist/nightwish/\d{4}/.*\.html$')
target_links = []

for link in soup.find_all('a', href=True):
    href = link['href']
    if pattern.match(href):
        target_links.append(href)
        print(href)

总结

优先选择方法一,依赖页面结构的解析方式更稳定,符合网页解析规范;正则适合结构不固定或需要复杂匹配规则的场景。

内容的提问来源于stack exchange,提问作者Wishmaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:40:34