小白爬虫问题求大神解答
本帖最后由 熊猫打字 于 2020-4-18 17:45 编辑作业题:写一个程序,依次访问文件中指定的站点,并将每个站点返回的内容依次存放到不同的文件中。
我在做这个作业时候,自己写了这样的代码:
import urllib.request
import chardet
import json
f= []
def readURL():
f = open(input('请输入您文件的路径:')).readlines()
for url in f:
response = urllib.request.urlopen(url).read()
encode = chardet.detect(response)['encoding']
for i in range(len(f)):
filename = str(i)+'.json'
if encode == 'GB2312':
encode = 'GBK'
txturl = response.decode('GBK')
with open(filename, 'w') as file_object:
json.dump(txturl,file_object)
else:
txturl = response.decode(encode)
with open(filename, 'w') as file_object:
json.dump(txturl,file_object)
readURL()
我的‘f’文档里有三个网站:
http://www.baidu.com
http://www.fishc.com
http://www.zhihu.com
问题1:运行之后,输出的json只有2,就是文件夹里只多了一个2.json(鱼c论坛的读取结果),其他都不出现,这是为什么啊?
问题2:如果返回的内容依次存放到txt文档,则python报错:
UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 214855: illegal multibyte sequence。已经进行了解码,为什么还会出现编码错误?
谢谢大神们 好像是第14-22行应该缩进在创建文件下面,我再理解一下
页:
[1]