第一次接触python 爬虫代码,这里主要是要注意编码的问题,从网上下载到的html数据是字节流,写到文件里面也需要用字节流,然后从文件里面读取后在匹配图片文件jpg的字符串需要解码为utf-8格式。 remodel.findall(htmlCode.decode(‘utf-8’)) 这行代码的htmlCode可以转换为filedata 是一样的效果
import urllib.request
import re
def getData():
page = urllib.request.urlopen(‘https://www.baidu.com/sf/vsearch?pd=video&tn=vsearch&lid=e08c0ba400008d63&ie=utf-8&rsv_pq=e08c0ba400008d63&wd=豆瓣&rsv_spt=5&rsv_t=455962lpqHmimoD7wauMCXYkgyRSTOGdua%2BG%2FgFaRImWqVQpZJkm%2BS64ZN7MRkZ%2F%2Fe64Cw&rsv_bp=1&f=8’)
htmlCode = page.read()
return htmlCode
htmlCode = getData()
print(htmlCode)
file = open(‘D:/urltest3.txt’,‘wb’)
file.write(htmlCode)
file.flush()
file.close()
file = open(‘D:/urltest3.txt’,‘rb’)
filedata = file.read()
restr = ‘src=".*?.jpg"’
remodel = re.compile(restr)
imglist = remodel.findall(htmlCode.decode(‘utf-8’))
print(len(imglist))
for img in imglist:
print(img)
本文介绍使用Python进行网页爬取时遇到的编码问题处理方法,重点讲解如何将从网络获取的字节流数据正确地解码为UTF-8格式,以便进行后续的数据解析和图片链接抓取。
920

被折叠的 条评论
为什么被折叠?



