发现更大的SEO世界
 找回密码
 注册
搜索
»首页»SEO培训 SEO论坛 SEO交流 帖子
发新帖
张伟,请到个人资料页面设置个人签名    

[已通过]使用python制作百万数据的sitemap文件

  1. #coding=utf-8
  2. # sitemap模板
  3. tpl = '<?xml version="1.0" encoding="utf-8"?>\n<urlset>\n<url>\n<loc>%s</loc>\n</url>\n</urlset>'
  4. tpl2 = '</loc>\n</url>\n<url>\n<loc>http:'
  5. tpl3 = '<?xml version="1.0" encoding="GB2312"?>\n<sitemapindex>\n%s</sitemapindex>'
  6. tpl4 = '<sitemap>\n<loc>%s</loc>\n</sitemap>\n'
  7. #基本参数配置
  8. k = 1        #计数器
  9. sitemap_name = 1        #sitemap编号
  10. sitemap_con = ''        #sitemap内容
  11. sitemap_on = 0        #sitemap是否已生成,1生成,0未生成
  12. sitemap_ex = 'seoqx-'        #sitemap前缀
  13. domain = 'http://www.test.com/'        #域名
  14. sitemap_count = 40000 #每个sitemap包含url条数
  15. url_source = '1.txt' #全部url地址
  16. # sitemap生成函数
  17. def creat_sitemap(name, con, tpl):
  18.         sitemap = open('%s%s.xml' % (sitemap_ex, name), 'w')
  19.         con = tpl % con
  20.         sitemap.write(con)
  21.         sitemap.close()       
  22.         print '%s%s.xml' % (sitemap_ex, name)
  23. # 生成sitemap
  24. with open(url_source) as f:       
  25.         for line in f:
  26.                 sitemap_con += line
  27.                 k += 1
  28.                 if sitemap_on == 1:
  29.                         sitemap_on = 0
  30.                 if k > sitemap_count:
  31.                         sitemap_con = 'h' + sitemap_con.replace('h', '', 1).replace('\n', '',).replace('http:', tpl2)
  32.                         creat_sitemap(sitemap_name, sitemap_con, tpl)
  33.                         # 初始化
  34.                         k = 1
  35.                         sitemap_name += 1
  36.                         sitemap_con = ''
  37.                         sitemap_on = 1                       
  38. if sitemap_on == 0:
  39.         sitemap_con = 'h' + sitemap_con.replace('h', '', 1).replace('\n', '',).replace('http:', tpl2)
  40.         creat_sitemap(sitemap_name, sitemap_con, tpl)
  41.         sitemap_con = ''
  42. # Sitemap索引
  43. for x in xrange(0,sitemap_name):
  44.         url = domain + sitemap_ex + str(x + 1) + '.xml'
  45.         sitemap_con += tpl4 % url
  46. creat_sitemap('sitemap', sitemap_con, tpl3)
复制代码


学习python是源于zero的《Python程序语言快速上手教程》,自己在传统机械行业维护企业站,网站数据不多,平均几百条数据。平时工作无外乎写写新闻发发外链,感到比较迷茫。
很认同zero的“有了需求再学习技术”。

ps:代码本地测试500w条数据用了53秒,本机2g内存,amd5200+ 老式台式机。大量数据用shell处理好像速度快,可惜对shell不是很懂。代码有错误欢迎拍砖,顺便求认证。

评分

参与人数 2赞同 +8 收起 理由
jnjoyo + 4 赞一个!
hwj888 + 4 已用到。

查看全部评分

发表于 2014-6-7 17:39:46
回复 收藏
why,请到个人资料页面设置个人签名    

好牛逼  
发表于 2014-6-17 00:26:08
回复 收藏
lx2st,哦    

测试了下很好用
发表于 2014-9-28 09:22:00
回复 收藏
huihuapp,做有技术的SEO    

不知道代码怎么用
发表于 2014-10-12 18:14:20
回复 收藏
seoman,SEO新手~    

我不知道代码怎么用。

楼主能发下用法。不懂python。
发表于 2014-10-22 17:27:44
回复 收藏
高级机器,请到个人资料页面设置个人签名    

伟哥好牛b
发表于 2015-7-28 20:39:07
回复 收藏
快速回复 返回顶部 返回列表