【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' PythonAttributeError:“NoneType”对象没有属性“文本”Python
【发布时间】:2018-10-15 17:08:28
【问题描述】:

我正在尝试使用 python 读取文件并将每一行作为函数的参数。我有一个 AttributeError: 'NoneType' object has no attribute 'text' 错误,我不明白如何解决它。这是我的代码

from requests import get
from bs4 import BeautifulSoup


file = open("applications.txt","r")
appArray = file.readlines()


def app_metadata(app_link):
    url = 'https://play.google.com/store/apps/details?id=' + app_link
    response = get(url)
    html_soup = BeautifulSoup(response.text, 'html.parser')
    print(html_soup.find(class_="AHFaub").text)


#print (appArray[0])
#print(type(appArray[0]))
#print(type("com.codebrewgames.pocketcitygame"))
app_metadata(appArray[2])

【问题讨论】:

  • 这里唯一合理的解释是responseNonehtml_soup.find(class_="AHFaub") 正在返回None
  • 请始终在您的问题中包含完整的错误回溯。
  • 请编辑您的问题并提供applications.txt文件
  • @g.d.d.c 指出了合理的解释。其中html-soup.find(class_="AHFaub") 几乎肯定是原因并返回None
  • 另外说明,资源文件applications.txt 永远不会关闭。确保执行 file.close() 来释放资源。更好的是使用with 子句来确保文件已关闭。例如with open('applications.txt', 'r') as fin: appArray=fin.readlines()

标签: python


【解决方案1】:

使用

appArray = [line.rstrip() for line in open('applications.txt')]                                                                                                     

每个字符串的末尾都有一个换行符。 Readlines 返回每行字符串的末尾带有一个换行符。并且请求将 appId 与换行符一起使用。像“com.android.chrome\n”而不是“com.android.chrome”。

【讨论】:

    【解决方案2】:

    以下行是您的错误的来源:

    print(html_soup.find(class_="AHFaub").text)
    

    html_soup.find(class_="AHFaub") 在解析响应时未能找到所需的部分,因此返回 None。一种解决方法如下:

    result = html_soup.find(class_="AHFaub")
    if result:
        print(result.text)
    

    这会在尝试打印之前检查是否有有效的结果。这被认为是一种 LBYL(先看再跳跃)方法。

    一种更 Pythonic 的方式是遵循 EAFP(请求宽恕比许可更容易)方法,如下所示:

    try:
        print(html_soup.find(class_="AHFaub").text)
    except AttributeError:
        print('Failed to parse url: {}'.format(url))
    

    此方法尝试执行打印,如果由于AttributeError 而失败,它将跳过它并执行except 块中的任何代码。

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2018-10-16
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多