利用python生成百万级URL的sitemap文件生成器

手里有一批百万级别的URL没有收录,想做成sitemap提交一下,跟python大神@赵彦刚同学提了这个需求,在我的“变态”要求之下,这个程序近乎完美,无论你给定多少URL,程序会自动判断,按最多50000条URL成生多个sitemap.xml文件,并且能自动生成siteamp索引文件,方便在百度站长平台提交。

在此分享一下这个python小程序。

用法:

利用python生成百万级URL的sitemap文件生成器
将需要生成sitemap的URL存为urls.txt,URL一行一个。

将sitemap.py放到跟url.txt一个文件夹里

直接运行python sitemap.py,几秒钟之后会在文件当前路径下生成sitemap文件夹,里面就是生成好的sitemap.xml及sitemapindex.xml,sitemapindex.xml在百度站长平台提交就OK了。

在使用这个程序之前,你需要对源码做一点小小的修改,即把原来的host = ‘http://seofangfa.com/’改为你自己的域名,并且后面一定要带上斜杠。

效果:

处理319W的URL,只用了6.6秒。

利用python生成百万级URL的sitemap文件生成器
利用python生成百万级URL的sitemap文件生成器

python源码:

复制源码,新建一个PY文件就可以使用了。

#coding:utf-8
#python生成sitemap,超过5万条数据自动生成新文件。
# from __future__ import division
#date:2016-3-18
#Author:赵彦刚@zhaoyangang.cn
#PM:方法@seofangfa.com
#
import os,datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

host = 'http://seofangfa.com/' #手动设置你网站的域名,别忘记了结尾的斜杠!
dir = os.popen('mkdir sitemap') #自动新建一个存放sitemap.xml的文件夹,默认叫sitemap,可自行修改。
path = 'sitemap/'#设定sitemap.xml文件存放的路径,别忘记了结尾的斜杠!
lastmod = datetime.date.today()


def add_file(j,f1,host,path):
	file_name = 'sitemap_%s.xml'%(j)
	f1.write("\n\n%s%s%s\n%s\n0.8\n"%(host,path,file_name,lastmod))
	f=open("%s%s"%(path,file_name),"a")
	f.write('\n')
	return f
	

#判断总的URL数
c = 0
for i in open('urls.txt'):
	url = i.strip()
	if len(url)==0:
		pass
	else:
		c+=1
print c
#判断需要生成的sitemap个数
file_num = c%50000
if file_num==0:
	file_num = c/50000
	print '总共有%s条URL,生成%s个sitemap文件'%(c,file_num)
else:
	file_num = (c/50000)+1
	print '总共有%s条URL,生成%s个sitemap文件'%(c,file_num)


#自动按5W条URL生成sitemap,并自动命名为sitemap_1.xml
i = 0
j = 2
f = open('%s/sitemap_1.xml'%(path),'w+')
f.write('\n')
f1 = open('%s/sitemapindex.xml'%(path),'a')
f1.write('\n')
f1.write("\n\n%s%s%s\n%s\n0.8\n"%(host,path,'sitemap_1.xml',lastmod))
for url in open("urls.txt"):
	url = url.strip()
	i += 1
	if i == 50000 or j == 50000:
		f.write('\n')
		f.close()
		i = 0
		f = add_file(j,f1,host,path)
		j += 1
	f.write("\n\n%s\n%s\n0.8\n"%(url,lastmod))

f.write('\n')
f1.write('\n')
f1.close()

文章转载于方法博客,版权归原作者所有。

打开微信扫一扫

王石头
聚划算购物

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: