python - 搜索列表时出现 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
解决方案
在附加之前检查一个'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
您指的是哪个。
推荐阅读
- c++ - 如何在一维数组的每个元素中都有多个 int 值?
- android - 如何从银行账户和 ifsc 代码生成 UPI 地址
- google-apis-explorer - 搜索控制台未显示新添加的(通过 API 调用)站点。google-api-explorer
- ios - Swift Combine:不需要输出相等的`append`?
- java - 无法将文本文件转换为 json
- javascript - CSS动画径向渐变?
- reactjs - Next.js 在 Kubernetes 上使用 Nginx
- excel - 条件格式 - 多个条件加上通配符文本匹配
- ios - 水平翻转视图。Xcode
- html - HTML中head标签内的body标签?