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

如何用Python提取网站链接?我的BeautifulSoup代码返回空列表求解答

问题分析与修复方案

错误点1:缺少requests库导入

你的代码调用了requests.get()但未导入requests库,运行时会直接报错,需先补上导入语句:

import requests

错误点2:页面结构更新,选择器失效

当前美联储演讲页面的标题元素类名已不是.itemTitle,网站更新了页面布局,现在每个演讲标题的链接嵌套在h3.eventlist__title标签下的<a>标签里,原选择器无法匹配到目标元素。

错误点3:未添加请求头,可能被反爬拦截

直接用requests.get()发起请求,容易被网站识别为爬虫并返回非预期内容,建议添加模拟浏览器的请求头规避拦截。

修复后的完整代码

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'https://www.federalreserve.gov/newsevents/speeches.htm'
# 添加请求头模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, features="lxml")

# 提取所有演讲标题的链接并补全为完整URL
speech_links = [f"https://www.federalreserve.gov{a['href']}" for a in soup.select('h3.eventlist__title a')]
print(speech_links)

运行上述代码即可获取到所有演讲的完整链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:52:44