4

我正在使用scrapy 来抓取一个多语言网站。对于每个对象,存在三种不同语言的版本。我使用搜索作为起点。不幸的是,搜索包含各种语言的 URL,这会导致解析时出现问题。

因此,我想在 URL 发出之前对其进行预处理。如果它们包含特定字符串,我想替换 URL 的那部分。

我的蜘蛛扩展了CrawlSpider. 我查看了文档并找到了make_request_from _url(url)导致这种尝试的方法:

def make_requests_from_url(self, url):                                                          
    """                                                                                         
    Override the original function go make sure only german URLs are                            
    being used. If french or italian URLs are detected, they're                                 
    rewritten.                                                                                  

    """                                                                                         
    if '/f/suche' in url:                                                                       
        self.log('French URL was rewritten: %s' % url)                                          
        url = url.replace('/f/suche/pages/', '/d/suche/seiten/')                                
    elif '/i/suche' in url:                                                                     
        self.log('Italian URL was rewritten: %s' % url)                                            
        url = url.replace('/i/suche/pagine/', '/d/suche/seiten/')                                  
    return super(MyMultilingualSpider, self).make_requests_from_url(url)                                                  

但这由于某种原因不起作用。在请求 URL 之前重写 URL 的最佳方法是什么?也许通过规则回调?

4

2 回答 2

8

Probably worth nothing an example since it took me about 30 minutes to figure it out:

rules = [
    Rule(SgmlLinkExtractor(allow = (all_subdomains,)), callback='parse_item', process_links='process_links')
]

def process_links(self,links):
    for link in links:
        link.url = "something_to_prepend%ssomething_to_append" % link.url
    return links
于 2013-11-23T21:27:38.050 回答
4

由于您已经扩展CrawlSpider,您可以使用它process_links()来处理由链接提取器提取的 URL(或者process_requests()如果您更喜欢在请求级别工作),在此处详细说明

于 2013-10-01T07:03:37.960 回答