【问题标题】:I get an Python BeautifulSoup None Type Error [duplicate]我得到一个 Python BeautifulSoup 无类型错误 [重复]
【发布时间】:2021-12-27 22:33:42
【问题描述】:
url = "https://www.imdb.com/chart/top/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.content,"html.parser")
puan = soup.find_all("tr")
for i in puan:
    puan2 = i.find_all("td",{"class":"ratingColumn"})
    for x in puan2:
        puan3 = x.find("strong")
        print(puan3.text)

我正在使用 BeautifulSoup。在我找到的结果中,我收到一个错误,因为列表中有 NoneType。如何从列表中删除 NoneType 部分

【问题讨论】:

  • 当find_all 返回无时,这意味着它没有找到您要查找的任何内容。具体来说,您的某些puan2 集合中没有<strong> 标记。如果您在内部循环中添加了print(x),您会看到。
  • 问题已解决,非常感谢

标签: python beautifulsoup nonetype


【解决方案1】:

添加一个简单的if 守卫就可以了:

if puan3 is not None:
    print(puan3.text)

【讨论】:

  • 非常感谢您的回复。因为你,我解决了问题。最好的问候
【解决方案2】:

会发生什么?

您的选择不是那么具体,因此您会得到一个结果集,其中还包含您不想选择的元素。

如何解决?

选择更具体的元素:

i.find_all("td",{"class":"imdbRating"})

或

for row in soup.select('table.chart tbody tr'):
    rating = row.select_one('.imdbRating strong').text
    print(rating)

以及额外的双重检查:

for row in soup.select('table.chart tbody tr'):
    rating = rating.text if (rating := row.select_one('.imdbRating strong')) else None
    print(rating)

示例(基于您的代码)

import requests
from bs4 import BeautifulSoup 

url = "https://www.imdb.com/chart/top/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.content,"html.parser")

puan = soup.find_all("tr")
for i in puan:
    puan2 = i.find_all("td",{"class":"imdbRating"})
    for x in puan2:
        puan3 = x.find("strong")
        print(puan3.text)

示例(css 选择器)

import requests
from bs4 import BeautifulSoup 

url = "https://www.imdb.com/chart/top/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.content,"html.parser")

for row in soup.select('table.chart tbody tr'):
    rating = rating.text if (rating := row.select_one('.imdbRating strong')) else None
    print(rating)

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2018-07-16
    • 2014-08-19
    • 2021-09-10
    相关资源
    最近更新 更多