各位老师这段代码报错的原因是什么如何解决谢谢了
import chardetimport urllib.request
import os
def url_open(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36')
response = urllib.request.urlopen(url)
html = response.read()
enc = chardet.detect(html)
enc = enc['encoding']
html = html.decode(enc)
return html
def get_page(url):
html = url_open(url)
a = html.find('thisclass')+11
b = html.find('<',a)
return html
def find_img (url):
html = url_open(url)
img_addrs = []
a = html.find('img src=')
while a != -1:
b = html.find('.jpg',a,a+255)
if b != -1:
img_addrs.append(html)
else:
b = a + 9
a = html.find('img src=',b)
return img_addrs
def save_img(name,img_addrs):
for each in img_addrs:
filename = each.split('/')[-1]
with open(filename,'wb') as f:
img = url_open(each)
f.write(img)
def download_mm(name='tupian',pages = 10):
os.mkdir(name)
os.chdir(name)
url = 'https://www.tupianzj.com/meinv/xinggan/'
page_num = int(get_page(url))
for i in range(pages):
page_num += 1
page_url = url +'list_176_'+str(page_num)+'.html'
img_addrs = find_img (page_url)
save_img(name,img_addrs)
if __name__ == '__main__':
download_mm()
错误类型TypeError: decode() argument 'encoding' must be str, not None
如何解决谢谢了
因为图片是没有编码的,所以不能什么都解码
import chardet
import urllib.request
import os
def url_open(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36')
response = urllib.request.urlopen(url)
html = response.read()
enc = chardet.detect(html)
enc = enc['encoding']
if enc: # 注意这里
html = html.decode(enc) # 注意这里
return html
def get_page(url):
html = url_open(url)
a = html.find('thisclass')+11
b = html.find('<',a)
return html
def find_img (url):
html = url_open(url)
img_addrs = []
a = html.find('img src=')
while a != -1:
b = html.find('.jpg',a,a+255)
if b != -1:
img_addrs.append(html)
else:
b = a + 9
a = html.find('img src=',b)
return img_addrs
def save_img(name,img_addrs):
for each in img_addrs:
filename = each.split('/')[-1]
with open(filename,'wb') as f:
img = url_open(each)
f.write(img)
def download_mm(name='tupian',pages = 10):
if not os.path.exists(name): # 注意这里
os.mkdir(name) # 注意这里
os.chdir(name)
url = 'https://www.tupianzj.com/meinv/xinggan/'
page_num = int(get_page(url))
for i in range(pages):
page_num += 1
page_url = url +'list_176_'+str(page_num)+'.html'
img_addrs = find_img (page_url)
save_img(name,img_addrs)
if __name__ == '__main__':
download_mm() 感谢老师讲解谢谢了 isdkz 发表于 2022-4-11 00:32
因为图片是没有编码的,所以不能什么都解码
感谢老师的讲解。谢谢了
页:
[1]