先我们要有一个带有图片的html文件,我们可以从中国国家地理网获取,打开网址:http://m.dili360.com/,任选一个自己喜欢的页面,点击鼠标右键,选择查看网页源码,将源码复制保存到本地就可以了。
实现爬虫我们分4个步骤:
1、读取保存在本地的html文件
2、解析并提取其中的图片链接
3、输出提取结果
4、保存提取结果为文件
# -*- coding:utf-8 -*-
#读取文件内容
def getHTMLLines(htmlpath):
f=open(htmlpath,'r',encoding='utf-8')
ls=f.readlines()
f.close()
return ls
#解析并提取其中的图片链接
def extractImageUrls(htmllist):
urls=[]
for line in htmllist:
if 'image' in line:
url=line.split('src=')[-1].split('"')[1]
if 'http' in url:
urls.append(url)
return urls
#输出提取的结果
def showResults(urls):
count=1
for url in urls:
print(f"第{count}个URL:{url}")
count+=1
def saveResults(filepath,urls):
f=open(filepath,'w')
for url in urls:
f.write(url+"\n")
f.close()
#保存提取结果为txt文件
def main():
inputfile='dili360.html'
outputfile='dili360-urls.txt'
htmlLines=getHTMLLines(inputfile)
imageUrls=extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile,imageUrls)
main()
看看运行结果吧: