用urllib.request函数爬程序的需要decode一下,转换成utf-8

#从豆瓣网中爬出版社的程序https://read.douban.com/provider/all
#最后并写入TXT文件当中
import re
import urllib.request
'''pat = "pyth[jsh]n"
sting1 = "wodepythjn"
relt = re.search(pat,sting1)
print(relt)
'''
f = urllib.request.urlopen("https://read.douban.com/provider/all")
f1 = f.read()
#请求的response是需要重新编码的就用到decode函数
f1=f1.decode("utf-8")
pat1 = 'class="name">(.*?)</div>'
f2 = re.compile(pat1).findall(str(f1))
#怎样将列表写在文本文档中
fh = open("E:/新电脑学习/Python脚本/13.txt","w")
for i in range(0,len(f2)):
    fh.write(fh[i]+"\n")
#用了fh.close之后才会在TXT文件中显示
fh.close()

又或者直接用

with open  open("E:/新电脑学习/Python脚本/13.txt","w") as f

#就不用写fh.close()就可以保存到TXT文件里了

猜你喜欢

转载自blog.csdn.net/weixin_42099676/article/details/81318606