为什么我的Python爬虫代码运行后终端没有任何输出?
代码无输出问题排查及修复方案
核心问题点
- 未添加请求头触发反爬:直接调用
requests.get()未携带User-Agent,目标站点拦截请求后返回非有效页面,无法解析到目标内容。 - 元素选择规则错误:
product-item-link是<a>标签的类名,代码中错误匹配<figure>标签,导致find_all返回空列表,后续循环完全不执行,因此没有任何输出。 - 域名拼写错误:拼接URL时将
topps.com误写为tops.com,即使拿到正确链接也会生成无效地址。 - 已导入依赖未使用:引入的
fake_useragent库可用于生成随机请求头规避反爬,但代码中未调用相关逻辑。
修复后代码
import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent def monitor(): # 构造带随机UA的请求头规避反爬 headers = { "User-Agent": UserAgent().random } source = requests.get('https://www.topps.com', headers=headers) # 先校验请求状态,避免无效解析 if source.status_code != 200: print(f"请求异常,状态码:{source.status_code}") return soup = BeautifulSoup(source.content, 'lxml') # 修正元素匹配规则,查找对应a标签 for a_tag in soup.find_all('a', class_='product-item-link'): href = a_tag.get('href') # 修正域名,同时兼容绝对/相对路径 if href.startswith('/'): url = "https://www.topps.com/cards-collectibles/topps-now" + href else: url = href print(url) monitor()
内容的提问来源于stack exchange,提问作者Ayman v2
相关产品推荐
相关产品推荐

