You need to enable JavaScript to run this app. 使用Python进行网页爬虫时content.find_all('a')运行报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

使用Python进行网页爬虫时content.find_all('a')运行报错如何解决?

问题排查与解决方法

for link in content.find_all('a') 报错的核心原因是 content 的值为 None,执行 soup.article 时目标网页的HTML结构里不存在顶层的 <article> 标签,调用 None.find_all() 就会抛出属性错误,可按照以下步骤排查修复:

第一步:验证请求返回的页面内容是否正常

很多网站会拦截无请求头的爬虫请求,你直接用request.urlopen没有带浏览器标识,返回的可能不是正常页面内容,自然找不到对应标签。
测试方法:在soup = BeautifulSoup(rawPage, "html5lib")行之后添加print(soup.prettify()),输出完整解析后的HTML结构,确认是否存在你需要的<article>标签。

第二步:添加请求头绕过反爬拦截

替换原请求逻辑,给请求添加模拟浏览器的User-Agent:

# 替换原来的 rawPage=request.urlopen(pageURL) 部分
req = request.Request(pageURL, headers={
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
})
rawPage = request.urlopen(req)

第三步:添加空值判断避免报错

不管页面返回是否正常,都先判断content是否存在再执行后续操作:

content = soup.article
if not content:
    print("未找到article标签,请检查页面结构")
    # 可根据实际页面结构调整查找的父标签,比如替换为soup.body
    exit()

第四步:修复代码其他逻辑错误

你原有代码还存在几个明显逻辑问题:

  • for循环内的变量操作、linksList.append没有缩进进循环体,只会执行一次
  • 给字典赋值时给变量加了引号,变成固定字符串,存入的都是"url"、"img"而非实际取到的变量值
  • 循环外的try块调用的link是循环内局部变量,循环未执行时该变量不存在会直接报错

修改后的完整参考代码:

from urllib import request
from bs4 import BeautifulSoup
import json

pageURL = "https://gamesnacks.com/embed/games/omnomrun"
# 添加请求头
req = request.Request(pageURL, headers={
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
})
rawPage = request.urlopen(req)

soup = BeautifulSoup(rawPage, "html5lib")
content = soup.article

linksList = []

# 先判断content是否存在
if content:
    for link in content.find_all('a'):
        try:
            url = link.get("href")
            img = link.get("src")
            text = link.span.text
            # 不要给变量加引号
            linksList.append({"url": url, "img": img, "text": text})
        except AttributeError:
            pass
else:
    print("未找到article标签,当前页面结构如下:")
    print(soup.prettify())

with open("links.json","w",encoding="utf-8") as links_file:
    json.dump(linksList, links_file, ensure_ascii=False)

print("the work is done")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 11:15:03