Python 3 实现在线xml sitemap索引文件提取URL到指定文件
毫无疑问,在SEO分析网站结构和开放搜索引擎端抓取页面数时,对sitemap文件的分析是最好的入手点。
通常规模不是太小的网站URL数量都会超过5万条,而搜索引擎要求单个sitemap文件的数量不能超过5万条,那么在此场景下sitemap索引文件便是好的解决方法,其用来存放单个sitemap文件的URL地址,在此基础上单个sitemap文件理论上可以囊括5万*5万=25亿,对网站来讲已经足够。
这里将会为大家提供Python 3实现的针对特定目标sitemap索引文件URL,提取其子sitemap文件,并提取子sitemap文件中的URL,记录对应的数量,并将提取的URL存放到本地的方法代码。
代码块有参考CSDN博主Yozz的部分代码,根据自己的使用场景进行了改良,具体代码如下:
# 功能介绍,通过在线访问网站sitemap-index文件链接,抓取其中的sitemap子文件,进一步抓取子文件提取其中的URL链接存放到电脑指定文件。
# 可用于特定场景下的小量级网站URL提取,手动提交 - 国内SEO
# 可用于对特定网站sitemap文件分析其核心页面数量和分布
# 可用于抓取目标分析网站的搜索引擎投放页面链接
# 杰西seo提供
import xml.dom.minidom as xmldom
import urllib.request
import xml
# 定义目标网站sitemap index文件的链接地址
index_url = "目标网站sitemap索引文件URL地址"
sitemap_path = 'sitemap子文件URL存放文件路径'
url_path = '抓取所有URL存放文件路径'
#访问sitemap index文件提取子sitemap URL,并且写入sitemap_url文件
http = urllib.request.Request(index_url)
http_run = urllib.request.urlopen(http)
dom = xml.dom.minidom.parse(http_run)
return_xml = dom.documentElement.getElementsByTagName('sitemap')
open(sitemap_path, 'w').close()
c1 = 0
for sitemap_xml in return_xml:
sitemap_url_loc = sitemap_xml.getElementsByTagName("loc")[0]
sitemap_url = sitemap_url_loc.firstChild.data
#print(a_url)
file = open(sitemap_path, 'a', encoding="utf-8")
file.write(sitemap_url+'\n')
file.close()
c1 += 1
continue
# 用于记录sitemap子文件的数量
print(f'共有{c1}个sitemap文件')
# 循环遍历访问[sitemap子文件URL存放文件]中的sitemap子文件URL链接
# c2用于记录所有sitemap文件中URL的数量
c2 = 0
for i in open(sitemap_path):
sitemap_url = i.strip()
if len(sitemap_url) == 0:
pass
else:
#访问单个子sitemap文件URL
http = urllib.request.Request(sitemap_url)
http_run = urllib.request.urlopen(http)
dom = xml.dom.minidom.parse(http_run)
return_xml = dom.documentElement.getElementsByTagName('url')
#open(url_path, 'w').close()
#c3 用于记录 单个sitemap子文件中的URL数量
c3 = 0
#循环遍历提取单个子sitemap文件中的URL
for url_xml in return_xml:
url_loc = url_xml.getElementsByTagName("loc")[0]
url = url_loc.firstChild.data
#print(a_url)
file = open(url_path, 'a', encoding="utf-8")
file.write(url + '\n')
file.close()
c2 += 1
c3 += 1
continue
#输出单个sitemap子文件中的URL数量
print(f'{sitemap_url}共有{c3}条URL')
# 输出所有sitemap文件中totalURL数量
print(f'总共有{c2}条URL')
关注杰西SEO获取更多SEO实操技巧