Python从sitemap里提取链接,如果是sitemap-index则抓取xml文件,再通过xml文件抓取url和时间,把url和时间放在一起,存入sqlite数据库
时间: 2023-04-02 09:03:57 浏览: 69
你可以使用Python的requests和BeautifulSoup库来从sitemap中提取链接。如果是sitemap-index,则需要先抓取xml文件,然后再从xml文件中抓取url和时间。可以使用Python的xml库来解析xml文件。最后,将url和时间放在一起,存入sqlite数据库中。
相关问题
从网站的sitemap地图(sitemap.xml地图)里抓取url和lastmod成对放入列表里,python代码实现
可以使用Python中的xml.etree.ElementTree模块来解析sitemap.xml文件,然后提取其中的url和lastmod信息。具体代码如下:
```python
import xml.etree.ElementTree as ET
# 解析sitemap.xml文件
tree = ET.parse('sitemap.xml')
root = tree.getroot()
# 遍历所有的url标签,提取url和lastmod信息
url_list = []
for url in root.iter('{http://www.sitemaps.org/schemas/sitemap/.9}url'):
loc = url.find('{http://www.sitemaps.org/schemas/sitemap/.9}loc').text
lastmod = url.find('{http://www.sitemaps.org/schemas/sitemap/.9}lastmod').text
url_list.append((loc, lastmod))
# 打印结果
print(url_list)
```
这段代码会将sitemap.xml文件中所有的url和lastmod信息提取出来,并以元组的形式存储在url_list列表中。
对网址https://www.u9seo.com/sitemap_index.xml进行解析,判断是不是sitemapindex,如果是则先解析子xml文件,再通过子xml文件抓取url和lastmod。如果不是sitemapindex,直接解析xml文件抓取url和lastmode,使用python实现
这是一个技术问题,我可以回答。根据网址https://www.u9seo.com/sitemap_index.xml的后缀名,可以判断它是一个sitemapindex文件。因此,需要先解析子xml文件,再通过子xml文件抓取url和lastmod。可以使用Python中的xml.etree.ElementTree模块来解析XML文件,具体实现可以参考以下代码:
```python
import requests
import xml.etree.ElementTree as ET
url = 'https://www.u9seo.com/sitemap_index.xml'
response = requests.get(url)
root = ET.fromstring(response.content)
if root.tag == '{http://www.sitemaps.org/schemas/sitemap/.9}sitemapindex':
for child in root:
sub_url = child.find('{http://www.sitemaps.org/schemas/sitemap/.9}loc').text
sub_response = requests.get(sub_url)
sub_root = ET.fromstring(sub_response.content)
for sub_child in sub_root:
url = sub_child.find('{http://www.sitemaps.org/schemas/sitemap/.9}loc').text
lastmod = sub_child.find('{http://www.sitemaps.org/schemas/sitemap/.9}lastmod').text
print(url, lastmod)
else:
for child in root:
url = child.find('{http://www.sitemaps.org/schemas/sitemap/.9}loc').text
lastmod = child.find('{http://www.sitemaps.org/schemas/sitemap/.9}lastmod').text
print(url, lastmod)
```
这段代码会先判断是否是sitemapindex文件,如果是,则解析子xml文件,抓取其中的url和lastmod;如果不是,则直接解析xml文件,抓取其中的url和lastmod。