问题描述
state_urls是字典,其中state是所有美国州名作为键,而url是有关它们的信息的URL。以下代码的要点是:对于dict中的每个键对,以状态名称保存一个文本文件,并使其包含该状态键链接的html内容。如果没有'.content',它会正常工作,但是会返回页面中所有的html,这远远超出了我的需要,但是一旦添加.content,错误就是AttributeError:'bytes'对象没有属性'text'
for state,url in state_urls.items():
r = requests.get(url).content
with open(state_dir + state + '.txt','w') as file:
file.write(r.text)
sleep(2)
解决方法
AttributeError:“字节”对象没有属性“文本”
查看变量r
中的内容-如果使用requests.get(url)
,则它包含Response
对象。如果您使用requests.get(url).content
,它将是content
对象的Response
属性,该属性是您下载的网页的文本(或更准确地说是bytes
)内容。
您正尝试使用变量r
再低几行:file.write(r.text)
。如果变量包含Response
对象,则可以这样做。但是,如果在此处存储.content
属性(即bytes
),则该属性不具有.text
属性。这应该工作
r = requests.get(url) # dont use content
with open(state_dir + state + '.txt','w') as file:
file.write(r.text) # r is Response,you can get its .text
sleep(2)