keanushelby 发表于 2021-3-11 19:19:20

关于调用request库出错的问题,急求助!

代码如下:

import requests
res = requests.get('https://read.qidian.com/chapter/293gD-TGBMUKVgi5xLJPjA2/0RYfKmL5c0_gn4SMoDUcDQ2.html')
res.raise_for_status
file = open('qidianxiaoshuo.txt' , 'wb')
for line in res.iter_content():
    file.write(line)
    file.close()

运行后报错:
Traceback (most recent call last):
File "D:\python\codes\demo1.py", line 6, in <module>
    file.write(line)
ValueError: write to closed file

使用with open :

import requests
res = requests.get('https://read.qidian.com/chapter/293gD-TGBMUKVgi5xLJPjA2/0RYfKmL5c0_gn4SMoDUcDQ2.html')
res.raise_for_status
with open('qidianxiaoshuo.txt' , 'wb') as file:
    for line in res.iter_content():
      file.write(line)
      file.close()

依然报错
Traceback (most recent call last):
File "D:\python\codes\demo1.py", line 6, in <module>
    file.write(line)
ValueError: write to closed file

求助大佬!

YunGuo 发表于 2021-3-13 17:18:04

import requests

header = {'user-agent': 'Mozilla/5.0'}
res = requests.get('https://read.qidian.com/chapter/293gD-TGBMUKVgi5xLJPjA2/0RYfKmL5c0_gn4SMoDUcDQ2.html',headers=header)
with open('qidian.txt', 'a', encoding='utf-8')as f:
    f.write(res.text)
页: [1]
查看完整版本: 关于调用request库出错的问题,急求助!