内容:提取国家地理中文网的图片链接(网站源码保存为HTML文档)
本案例可以分成以下步骤:
1.读取保存在本地的HTML文档
2.解析并提取其中的图片链接
3.输出提取结果到屏幕
4.保存提取结果为文件
采用自顶而下的的设计思路。
以下是国家地理中文网的网页源码一角
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 'img' in line:
url=line.split('src')[-1].split('"')[1]
if 'http' in url:
urls.append(url)
return urls
def showResults(urls):
count=0
for url in urls:
print('第{:2}个URL:{}'.format(count,url))
count+=1
def saveResults(filepath,urls):
f=open(filepath,"w")
for url in urls:
f.write(url+"\n")
f.close()
def main():
inputfile='nationalgeographic.html'
outputfile='nationalgeographic-urls.txt'
htmlLines=getHTMLlines(inputfile)
imageUrls=extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile,imageUrls)
main()
附上py源代码:运行程序可以得到几十个图片链接,见下截图。
可以复制链接去浏览器打开,就可以看到爬取的效果了,这是其中随机一个链接对应的图片。
py例题案例保存下来,以便更加深入的学习,不喜勿喷,谢谢。