这样写我遇到一个新的错误如下:Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\hello.py", line 34, in <module>
get_img(open_url(url))
File "C:\Users\Administrator\Desktop\hello.py", line 30, in get_img
f.write(img)
TypeError: a bytes-like object is required, not 'str'
代码:import re
import urllib.request
import os
def open_url(url): #设置访问对象
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8',"replace")
return html
def get_img(html): #获取图片
p = r'<img src="([^"]+\.jpg)'
imglist = re.findall(p,html)
'''
for each in imglist:
print(each)
'''
count = 0
for each in imglist:
count += 1
filename = '%d.jpg'
pic = 'http:' + each
with open(filename%count, 'wb') as f:
img = open_url(pic)
f.write(img)
if __name__ == '__main__':
url ='http://jandan.net/ooxx/MjAyMDAxMDMtNjk=#comments'
get_img(open_url(url))
|