2017-09-15 69 views
1

嗨我只想刮掉其日期比特定日期更新的页面。如果比上次修改日期更新,刮去网址-Scrapy

例如:如果lastmod是2017/14/9或更新版本,只能刮掉网址。

我使用此代码来凑所有的页面,但我不能限制它的基础上lastmod日期:

import requests 
from scrapy.spiders import SitemapSpider 
from urllib.parse import urljoin 


class MySpider(SitemapSpider): 
    name = 'sitemap_spider' 
    robots_url = 'http://www.example.org/robots.txt' 

    sitemap_urls = [robots_url] 
    sitemap_follow = ['products-eg-ar'] 

    def parse(self, response): 
     print(response.url) 

这是我robots.txt

sitemap: /sitemap-products-eg-ar-index-1-local.xml 

sitemap-products-eg-ar-index-1-local.xml包含:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> 
    <sitemap> 
    <loc>/sitemap-products-eg-ar-1.xml</loc> 
    </sitemap> 
    <sitemap> 
    <loc>/sitemaps/sitemap-products-eg-ar-2.xml</loc> 
    </sitemap> 
</sitemapindex> 

sitemap-products-eg-ar-2.xml包含:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> 
<url> 
    <loc>/product-8112041/i/</loc> 
    <priority>0.8</priority> 
    <lastmod>2017-06-17</lastmod> 
    <changefreq>daily</changefreq> 
</url> 
</urset> 

回答

1

这是标准SitemapSpider类不可能的。你将不得不继承它并修改它的_parse_sitemap方法,它将处理urlset。由于该方法内部使用sitemap模块中的iterloc函数,因此更为脏的解决方案只是重新定义该函数以考虑lastmod元素。类似这样的:

import datetime 
import scrapy 

oldest = datetime.datetime.strptime('2017-09-14', '%Y-%m-%d') 

def _iterloc(it, alt=False): 
    for d in it: 
     lastmod = datetime.datetime.strptime(d['lastmod'], '%Y-%m-%d') 
     if lastmod > oldest: 
      yield d['loc'] 

      # Also consider alternate URLs (xhtml:link rel="alternate") 
      if alt and 'alternate' in d: 
       for l in d['alternate']: 
        yield l 

scrapy.spiders.sitemap.iterloc = _iterloc 

# your spider code here