首页 > 解决方案 > open: integer is required 需要什么参数错误

问题描述

我正面临公开声明的问题。我不知道为什么期待一个整数

import urllib

site_url='https://en.wikipedia.org/wiki/Boroughs_of_New_York_City'
r = urllib.request.urlopen(site_url)
site_content = r.read().decode('utf-8')

with open('saved_page.html', 'w') as f:
    f.write(site_content)

这是错误

TypeError                                 Traceback (most recent call last)
<ipython-input-2-993aea7cff16> in <module>
     12 site_content = r.read().decode('utf-8')
     13 
---> 14 with open('saved_page.html', 'w','utf-8') as f:
     15     f.write(site_content)

TypeError: an integer is required (got type str)

标签: pythonweb-scraping

解决方案


您将 'utf-8' 作为第三个位置参数传递。但是,当您查看文档时,您会发现这实际上是针对buffering. 编码是在那之后。因此,您应该将其作为关键字参数传递:

with open('saved_page.html', 'w', encoding='utf-8') as f:
    f.write(site_content)

推荐阅读