应用题
5. 考生文件夹文件sweb.html保存了一个网页的源代码,其中,“href=”引导后面会有一个URL链接,例如:href="http://news.sina.com.cn/feedback/post.html",其中,有一种链接前后都有空格,且双引号内以“http://”开头。
请编写程序,解析这个文件,提取出现符合上述特征的URL链接,每个链接一行,保存到“text-urls.txt”文件中,格式如下:
URL1
URL2
(略)
【正确答案】fi=open("sweb.html","r",encoding='utf-8')
fo=open("text-urls.txt","w",encoding='utf-8')
txt=fi.read()
ls=txt.split(" ")
urls=[]
for item in ls:
if item[:5]=="href="and item[6:13]=="http://":
urls.append(item[6:-1])
for item in urls:
fo.write(item+"\n")
fi.close()
fo.close()
【答案解析】