我遇到了开放语句的问题。我不知道为什么期待一个整数
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)
你传递了'utf-8'作为第三个位置参数。但是,当您查找文档时,您会发现这实际上是针对buffering
的。编码在那之后。所以你应该把它作为一个关键字参数传递:
with open('saved_page.html', 'w', encoding='utf-8') as f:
f.write(site_content)
下面的代码在python 3.6.3下工作
import urllib.request as request
site_url = 'https://en.wikipedia.org/wiki/Boroughs_of_New_York_City'
r = request.urlopen(site_url)
site_content = r.read().decode('utf-8')
with open('saved_page.html', 'w', encoding='utf-8') as f:
f.write(site_content)