【问题标题】:How to exclude 404 error urls in sitemap.xml?如何在 sitemap.xml 中排除 404 错误 URL?
【发布时间】:2022-10-05 16:33:18
【问题描述】:

我正在尝试使用此在线代码创建站点地图,但我不知道如何将其写入 XML 文件。

from usp.tree import sitemap_tree_for_homepage

tree = sitemap_tree_for_homepage(\'\')
print(tree)

for page in tree.all_pages():
    print(page)
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如它目前所写的那样,很难准确地说出你在问什么。

标签: python sitemap.xml


【解决方案1】:

站点地图布局如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <url>

      <loc>http://www.example.com/</loc>

      <lastmod>2005-01-01</lastmod>

      <changefreq>monthly</changefreq>

      <priority>0.8</priority>

   </url>

</urlset> 

this 线程中,您可以阅读如何创建 xml 文件:

from usp.tree import sitemap_tree_for_homepage
import xml.etree.cElementTree as ET
import simplejson as json

tree = sitemap_tree_for_homepage('https://www.nytimes.com/')

root = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")

for page in tree.all_pages():
    url = page.url
    prio = json.dumps(page.priority, use_decimal=True)
    # format YYYY-MM-DDThh:mmTZD see: https://www.w3.org/TR/NOTE-datetime
    lm = page.last_modified.strftime("%Y-%m-%dT%H:%M%z")
    cf = page.change_frequency.value
    urlel = ET.SubElement(root, "url")
    ET.SubElement(urlel, "loc").text = url
    ET.SubElement(urlel, "lastmod").text = lm
    ET.SubElement(urlel, "changefreq").text = cf
    ET.SubElement(urlel, "priority").text = prio

ET.indent(root, "  ") # pretty print
xmltree = ET.ElementTree(root)
xmltree.write("sitemap.xml", encoding="utf-8", xml_declaration=True )
    

如果您希望 lastmod 成为今天的日期。从日期时间导入日期。

from datetime import date

并更换

page.last_modified.strftime("%Y-%m-%dT%H:%M%z")

date.today().strftime("%Y-%m-%dT%H:%M%z")

站点地图.xml

<?xml version='1.0' encoding='utf-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://www.example.com/</loc>
    <lastmod>2022-07-19T15:24+0000</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>https://www.example.com/about</loc>
    <lastmod>2022-07-19T15:24+0000</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.8</priority>
  </url>

</urlset>

如果您使用https://www.example.com/ 作为您的网址,您将不会得到上面的输出。因为 example.com 没有 sitemap.xml。所以使用不同的网址。

【讨论】:

  • @May 那是因为它采用了网站站点地图中的日期
  • @May 的意思是我解决了你的问题!?
猜你喜欢
  • 1970-01-01
  • 2021-08-02
  • 2012-10-06
  • 1970-01-01
  • 2017-07-08
  • 2015-06-04
  • 2016-07-13
  • 1970-01-01
  • 2013-05-23
相关资源
最近更新 更多