首页 > 解决方案 > 搜索列表时出现 TypeError

问题描述

我正在处理的项目获取并打开 wiki 主页,打开页面上属于类别的每个链接,然后获取每个类别页面上的前 10 个链接并将它们写入文件。

代码:

url_list = open('url_list', 'w')

counter = 0

urls = []

html = urllib.request.urlopen('https://commons.wikipedia.org/wiki/Main_Page')

soup = bs.BeautifulSoup(html, 'lxml')

for item in soup.find_all('a'):
    urls.append(item.get('href'))

    for item in urls:

        if 'Category' in item:
            page = urllib.request.urlopen('https://commons.wikipedia.org/' + item)

            soup = bs.BeautifulSoup(page, 'lmxl')

            if counter < 10:
                for item in soup.find_all('a'):
                    url_list.write(item.get('href'))

                    counter += 1

url_list.close()

当我运行代码时,我得到了这个 TypeError:

Traceback (most recent call last):
File "/Users/huntergary/Web_links.py", line 42, in <module>
main()
File "/Users/huntergary/Web_links.py", line 23, in main
if 'Category' in item:
TypeError: argument of type 'NoneType' is not iterable

标签: pythonbeautifulsouptypeerrorwritefile

解决方案


在附加之前检查一个'href'项目是否被返回,或者item在尝试查看它是否包含之前检查'Category'

href = item.get('href')
if href is not None:
    urls.append(href)

或者,

if item is not None and 'Category' in item:

任何一种方法都应该阻止您检查列表中None的对象urls

作为旁注,您应该考虑不要item在这样的嵌套上下文中重复使用变量名三次。在更深层的代码中,并不总是很清楚item您指的是哪个。


推荐阅读