【问题标题】:Python:AttributeError: 'NoneType' object has no attribute 'split'Python:AttributeError:“NoneType”对象没有属性“split”
【发布时间】:2016-02-14 04:52:20
【问题描述】:
 h = soup.findAll("div", {"id": "products"})
for row in h:
    b = row.findAll("div", {"class": "gd-row"})
    for a in b:
        c = a.findAll("div", {"class": "gd-col"})
        for d in c:
            e = d.findAll("div", {"class": "product-unit"})
            for f in e:
                g = f.findAll("div", {"class": "pu-details"})
                for h in g:
                    i = h.findAll("div", {"class": "pu-title"})
                    for k in i:
                        l = k.findAll('a')
                        for z in l:
                            text = z.get('href')

                            title = str(z.get_text().strip())
                            urldict.update({counter: text})
                            print (str(counter) + ')' + title)

                            titlelist.append(title)

                            counter = counter + 1


print ("\nSeems we found more than one same mobile type, help us by selecting appropiate model \n")
user_choice = input("\nEnter your choice (number) which matches exactly:")
url_from_search = "http://www.xyzabc.com{}".format(
    urldict.get(user_choice).split('&')[0])

谁能帮我解决这个问题?我正在尝试在 beautifulsoup 的帮助下进行 html 解析。上面给出的代码是抛出属性错误。可能是什么问题?如果可能,请帮助我。

【问题讨论】:

  • 当您发布错误时,最好发布堆栈跟踪或至少发布错误发生的错误。 Python 为您提供堆栈跟踪以帮助调试,...所以传递它!

标签: python html parsing split beautifulsoup


【解决方案1】:

显然,user_choice 键不在 urldict 字典中,urldict.get(user_choice) 返回 None。假设您使用的是 Python 3 并且您的 urldict 键是整数,您需要在查找之前将输入数字转换为整数:

user_choice = int(input("\nEnter your choice (number) which matches exactly:"))
url_from_search = "http://www.acxcs.com{}".format(
    urldict.get(user_choice).split('&')[0])

此外,您可能应该更好地处理“丢失钥匙”的情况。例如:

user_choice = int(input("\nEnter your choice (number) which matches exactly:"))
if user_choice not in urldict:
    print("Error, the number is not valid")
else:
    url_from_search = "http://www.acxcs.com{}".format(urldict[user_choice].split('&')[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多