1. 程式人生 > >LxmlLinkExtractor類參數解析

LxmlLinkExtractor類參數解析

響應 selector ttr 規範化 urn def nco get 應用

LxmlLinkExtractor

LxmlLinkExtractor 是一種強大的鏈接提取器,使用他能很方便的進行選項過濾,他是通過xml中強大的HTMLParser實現的

源代碼如下:

class LxmlLinkExtractor(FilteringLinkExtractor):

    def __init__(self, allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths=(),
                 tags=(‘a‘, ‘area‘), attrs=(‘href‘,), canonicalize=
False, unique=True, process_value=None, deny_extensions=None, restrict_css=(), strip=True): tags, attrs = set(arg_to_iter(tags)), set(arg_to_iter(attrs)) tag_func = lambda x: x in tags attr_func = lambda x: x in attrs lx = LxmlParserLinkExtractor( tag=
tag_func, attr=attr_func, unique=unique, process=process_value, strip=strip, canonicalized=canonicalize ) super(LxmlLinkExtractor, self).__init__(lx, allow=allow, deny=deny, allow_domains=allow_domains, deny_domains=
deny_domains, restrict_xpaths=restrict_xpaths, restrict_css=restrict_css, canonicalize=canonicalize, deny_extensions=deny_extensions) def extract_links(self, response): base_url = get_base_url(response) if self.restrict_xpaths: docs = [subdoc for x in self.restrict_xpaths for subdoc in response.xpath(x)] else: docs = [response.selector] all_links = [] for doc in docs: links = self._extract_links(doc, response.url, response.encoding, base_url) all_links.extend(self._process_links(links)) return unique_list(all_links)

參數說明:

  • allow=(一個正則表達式或者正則表達式的列表) 只有與之相匹配的url才能被提取出來
  • deny=(一個正則表達式或者正則表達式的列表) 一個正則表達式(或正則表達式列表),(絕對)urls必須匹配才能排除(即不提取)。它優先於allow參數。如果沒有給出(或為空),它不會排除任何鏈接。
  • allow_domains=(str或者list) 允許提取鏈接的域名的字符串列表或者單個字符串,例如:allow_domain = [‘baidu.com‘]則只能提取baidu.com的域名內的鏈接
  • deny_domains=() 與上述的意思剛剛相反
  • restrict_xpaths=(str或list) - 是一個XPath(或XPath的列表),它定義響應中應從中提取鏈接的區域。如果給出,只有那些XPath選擇的文本將被掃描鏈接。

  • targs=(‘a‘,‘area‘) 標簽或在提取鏈接時要考慮的標簽列表。默認為。(‘a‘, ‘area‘) 也就是默認只有a標簽與area標簽的鏈接才能被提取

  • attrs=(‘href‘,) 在查找要提取的鏈接時應該考慮的屬性或屬性列表(僅適用於參數中指定的那些標簽tags )。默認為(‘href‘,)
  • cononicalize=(boolean) 規範化每個提取的url(使用w3lib.url.canonicalize_url)。默認為True。

  • unique=(boolean) 是否應對提取的鏈接應用重復過濾。

  • process_value=(callable) 接收從標簽提取的每個值和掃描的屬性並且可以修改值並返回新值的函數,或者返回None以完全忽略鏈接。如果沒有給出,那麽process_value默認為:lambda x:x
    例如,要從此代碼中提取鏈接:

    <a href="javascript:goToPage(‘../other/page.html‘); return false">Link text</a>

    您可以使用以下功能process_value:

    def process_value(value):
    m = re.search("javascript:goToPage\(‘(.*?)‘", value)
    if m:
        return m.group(1)
  • deny_extensions=(list) -包含在提取鏈接時應該忽略的擴展的單個值或字符串列表。如果沒有給出,它將默認為IGNORED_EXTENSIONS在scrapy.linkextractors包中定義的 列表 。
  • restrict_css=() 一個CSS選擇器(或選擇器列表),用於定義響應中應提取鏈接的區域。有相同的行為restrict_xpaths。
  • strip=

LxmlLinkExtractor類參數解析