当前位置:
首页 > Python基础教程 >
-
如何使用Python来生成sitemap
在做网站项目时,经常会使用脚本生成sitemap, 便于爬虫爬取,有利于SEO。 那么如何使用Python来生成sitemap呢?下面我们来研究一番。
安装lxml
首先需要pip install lxml安装lxml库。
如果你在ubuntu上遇到了以下错误:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include "libxml/xmlversion.h" compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Cleaning up... Removing temporary dir /tmp/pip_build_root ... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-O4cIn6-record/install-record .txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/lxml Exception information: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py" , line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py" , line 283, in run requirement_set. install (install_options, global_options, root=options.root_path) File "/usr/lib/python2.7/dist-packages/pip/req.py" , line 1435, in install requirement. install (install_options, global_options, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/req.py" , line 706, in install cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False) File "/usr/lib/python2.7/dist-packages/pip/util.py" , line 697, in call_subprocess % (command_desc, proc.returncode, cwd)) InstallationError: Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-O4cIn6-record/install-record .txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/lxml |
请安装以下依赖:
1
|
sudo apt-get install libxml2-dev libxslt1-dev |
Python代码
下面是生成sitemap和sitemapindex索引的代码,可以按照需求传入需要的参数,或者增加字段:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#!/usr/bin/env python # -*- coding:utf-8 -*- import io import re from lxml import etree def generate_xml(filename, url_list): """Generate a new xml file use url_list""" root = etree.Element( 'urlset' , xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9" ) for each in url_list: url = etree.Element( 'url' ) loc = etree.Element( 'loc' ) loc.text = each url.append(loc) root.append(url) header = u '<?xml version="1.0" encoding="UTF-8"?>\n' s = etree.tostring(root, encoding = 'utf-8' , pretty_print = True ) with io. open (filename, 'w' , encoding = 'utf-8' ) as f: f.write( unicode (header + s)) def update_xml(filename, url_list): """Add new url_list to origin xml file.""" f = open (filename, 'r' ) lines = [i.strip() for i in f.readlines()] f.close() old_url_list = [] for each_line in lines: d = re.findall( '<loc>(http:\/\/.+)<\/loc>' , each_line) old_url_list + = d url_list + = old_url_list generate_xml(filename, url_list) def generatr_xml_index(filename, sitemap_list, lastmod_list): """Generate sitemap index xml file.""" root = etree.Element( 'sitemapindex' , xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9" ) for each_sitemap, each_lastmod in zip (sitemap_list, lastmod_list): sitemap = etree.Element( 'sitemap' ) loc = etree.Element( 'loc' ) loc.text = each_sitemap lastmod = etree.Element( 'lastmod' ) lastmod.text = each_lastmod sitemap.append(loc) sitemap.append(lastmod) root.append(sitemap) header = u '<?xml version="1.0" encoding="UTF-8"?>\n' s = etree.tostring(root, encoding = 'utf-8' , pretty_print = True ) with io. open (filename, 'w' , encoding = 'utf-8' ) as f: f.write( unicode (header + s)) if __name__ = = '__main__' : urls = [ 'http://www.baidu.com' ] * 10 mods = [ '2004-10-01T18:23:17+00:00' ] * 10 generatr_xml_index( 'index.xml' , urls, mods) |
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式