这周二营长SEO有个需求,需要批量生成sitemap,由于百度站长平台对单个sitemap文件的url数量的限制,当url数量大于50000时,需要生成新的文件,特此写了个python脚本,工作日时间紧,当时只是写了个每次生成50000个的脚本,不能自动生成文件,周末整理了下。这个脚本无url数量限制。百万级的url生成sitemap文件以及索引文件轻轻松松。
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
author = 'heziliang'
item = 1
f = open('item_%s.xml' % item, r'a+')
f_index = open('index_item.xml',r'a+')
f_index.write('<?xml version="1.0" encoding="utf-8"?>'+'\n')
f_index.write('<sitemapindex>'+'\n')
for i, line in enumerate(open('urls.txt')):
if i % 50000==0:
print i
f.write('<?xml version="1.0" encoding="utf-8"?>'+'\n')
f.write('<urlset>'+'\n')
f.write(' '+'<url>'+'\n')
f.write(' '+'<loc>'+line.strip()+'</loc>'+'\n')
f.write(' '+'<lastmod>'+str(datetime.date.today())+'</lastmod>'+'\n')
f.write(' '+'<changefreq>daily</changefreq>'+'\n')
f.write(' '+'<priority>1.0</priority>'+'\n')
f.write(' '+'</url>'+'\n')
if i % 50000==49999:
f.write('</urlset>')
f.close()
f_index.write(' '+'<sitemap>'+'\n')
f_index.write(' '+'<loc>item_%s.xml</loc>'%item+'\n')
f_index.write(' '+'<lastmod>'+str(datetime.date.today())+'</lastmod>'+'\n')
f_index.write(' '+'</sitemap>'+'\n')
item += 1
f = open('item_%s.xml' % item, r'a+')
f.write('</urlset>')
f.close()
f_index.write('</sitemapindex>')
f_index.close()生成完毕以后直接在站长平台提交index_item.xml就可以,更多脚本在github:https://github.com/hzlRises