代码之家  ›  专栏  ›  技术社区  ›  Amar

漂亮汤错误:“NoneType”对象没有属性“find\u all”

  •  0
  • Amar  · 技术社区  · 2 年前

    我收到以下错误:

    ---> 14 content = s.find_all('p')
    AttributeError: 'NoneType' object has no attribute 'find_all'
    

    运行以下脚本时:

    r = requests.get('https://www.marketsandmarkets.com/Market-Reports/rocket-missile-market-203298804.html/')
    soup = BeautifulSoup(r.content, 'html.parser')
    s = soup.find('div', class_='entry-content') 
    content = s.find_all('p')
    print(content)   
    

    它适用于某些URL,但对于其他URL,它会给出一个属性错误。不知道为什么会这样。

    1 回复  |  直到 2 年前
        1
  •  0
  •   joanis Ankur Kumar Srivastava    2 年前

    什么时候 soup.find 没有找到任何东西,它返回 None s.find_all 呼叫 if s: if s in not None: .

    因此,您的代码变成:

    r = requests.get('https://www.marketsandmarkets.com/Market-Reports/rocket-missile-market-203298804.html/')
    soup = BeautifulSoup(r.content, 'html.parser')
    s = soup.find('div', class_='entry-content') 
    if s is not None:
        content = s.find_all('p')
        print(content) 
    else:
        print("Didn't find what I was looking for...")
    

    或者可能:

    content = s.find_all('p') if s is not None else []
    print(content)
    

    裁判: https://crummy.com/software/BeautifulSoup/bs4/doc/#find