Python:AttributeError: 'NoneType' 对象没有属性 'split'

标签 python html parsing split beautifulsoup

 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 解析。上面给出的代码抛出属性错误。可能是什么问题?如果可能的话请帮助我。

最佳答案

显然,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])

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

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])

关于Python:AttributeError: 'NoneType' 对象没有属性 'split',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388479/

相关文章:

php - include_once 似乎将所需的页面打印到 html 中

jquery - 如何根据复选框值设置标签样式?

PHP 不解析双引号内的变量

java - 如何使用 java-parser 和 java-symbol-solver 推断函数所有参数的类型?

python - 在 Python 中连续解析文件

python - Pandas :来自聚合列的多条形图

python - 匹配但不返回两个匹配之间的正则表达式

python - 如何在终端窗口中打印/显示 telnet session 的输出 (Python)

python - 在 python 中将原始位发送到终端

javascript - 在光标位置插入笑脸