2016-04-28 5 views
0

私は例を得た治療でリンクパターンがどのように働くのか苦労しています。誰かに書き方を教えてもらえますか?私は治療のためのリンクパターンを書く方法を理解していません

def parse(self, response): 

    hxs    = scrapy.Selector(response) 
    links   = hxs.xpath("//a/@href").extract()   
    #We stored already crawled links in this list 
    crawledLinks = [] 



    #Pattern to check proper link 
    linkPattern  = re.compile("^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*@)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+))?$") 



    for link in links: 
     # If it is a proper link and is not checked yet, yield it to the Spider 
     if linkPattern.match(link) and not link in crawledLinks: 
      crawledLinks.append(link) 
      yield Request(link, self.parse) 


    item = MS_homeItem() 
    item['name'] = hxs.xpath('//*[@id="product-detail-page"]/li[4]/div/div[2]/h1').extract() 
    yield item 

すべてのヘルプは素晴らしいだろうおかげでジェームズ

+0

自動的に重複したURLをフィルタリングします。 – Steve

答えて

0

Pythonはregular expressions(正規表現)として知られている非常に一般的な機能をサポートしています。より簡単な例を次に示します。

import re 

strings = [ 
    "cat", 
    "cut", 
    "bird", 
    "catnip", 
    "cute", 
] 

pattern = r"c.t" 
regex = re.compile(pattern) 

for string in strings: 
    if regex.match(string): 
     result = 'yes' 
    else: 
     result = 'no' 

    print("{} => {}".format(string, result)) 

--output:-- 
cat => yes 
cut => yes 
bird => no 
catnip => yes 
cute => yes 

パターンでは、.は任意の文字に一致します。

http://www.google.com

だけでなく、より複雑なURL:

linkPatternは次のようなものと一致した長い複雑なパターンです。 URLは非常に複雑で、あなたは約hereを読むことができます。

+0

ありがとうございます。それは本当に役立ちます。 –

関連する問題