weixin_45947411 2019-12-31 15:41 采纳率: 0%
浏览 859

用BS爬取网页内容之后提取标签属性,显示AttributeError: 'NoneType' object has no attribute 'text'。用print可以成功提取出文本内容,放在循环里就出错。

用BS爬取网页内容之后标签属性一直出错,显示AttributeError: 'NoneType' object has no attribute 'text'

我用print在循环之前试过是可以成功提取出文本内容的,不知道为什么在循环里就不行。求大神解惑!

#s = content[0].find('h5',class_="result-sub-header")
#print(s.text.strip())

#遍历content,取出结果
#因为find_all返回的是一个list,再对list用find_all时,需要指定元素[0]
for i in range(len(content)): 
    #提取标题
    t = content[i].find('a',class_="title")
    title = t.text.strip()
    #提取链接
    url = 'https://www.forrester.com'+t['href']
    #提取摘要
    s = content[i].find('h5',class_="result-sub-header")
    summary = s.text.strip()

    #将提取的内容放在列表paper中
    paper = [title,'Cloud Migration',url,summary]
    #把每个paper加到paperlist
    paperlist.append(paper) 
  • 写回答

1条回答 默认 最新

  • Stitch . 新星创作者: 编程框架技术领域 2024-07-27 10:51
    关注

    出现 AttributeError: 'NoneType' object has no attribute 'text' 这个错误通常意味着你尝试从一个 None 类型的对象上调用 .text 属性。在你的代码中,这通常发生在 find 方法没有找到任何匹配的标签时。find 方法如果没有找到任何匹配的元素,会返回 None。

    在你的循环中,这个问题可能由以下几个原因引起:

    某些 content[i] 不包含预期的标签:可能不是所有的 content[i] 都包含 a 标签或 h5 标签,或者这些标签的类名不完全匹配。
    类名不匹配:确保类名 title 和 result-sub-header 确实是页面中使用的类名,且没有拼写错误或额外的空格。
    为了解决这个问题,你可以添加一些检查来确保 find 方法返回的不是 None,然后再尝试访问 .text 属性。这里是如何修改你的代码:

    
    paperlist = []  
      
    # 遍历content,取出结果  
    for i in range(len(content)):  
        # 提取标题  
        t = content[i].find('a', class_="title")  
        if t is not None:  
            title = t.text.strip()  
        else:  
            title = "No title found"  # 或者你可以决定如何处理这种情况  
      
        # 提取链接  
        if t is not None:  
            url = 'https://www.forrester.com' + t['href']  
        else:  
            url = "No URL found"  
      
        # 提取摘要  
        s = content[i].find('h5', class_="result-sub-header")  
        if s is not None:  
            summary = s.text.strip()  
        else:  
            summary = "No summary found"  
      
        # 将提取的内容放在列表paper中  
        paper = [title, 'Cloud Migration', url, summary]  
        # 把每个paper加到paperlist  
        paperlist.append(paper)  
    
    

    现在你可以使用paperlist了

    这个修改确保了在尝试访问 .text 或 ['href'] 之前,你已经检查了 find 方法的返回值是否为 None。这样可以避免 AttributeError 并允许你更优雅地处理那些没有预期标签的情况。

    评论

报告相同问题?