1. 程式人生 > >用urllib.request函式爬程式的需要decode一下,轉換成utf-8

用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檔案裡了