【问题标题】:How can i obtain a domain name with Scrapy?如何使用 Scrapy 获取域名?
【发布时间】:2015-11-06 19:38:44
【问题描述】:

我知道 html 中有一个命令:var x = document.domain; 可以获取域,但是我如何在 Scrapy 中实现它以便获取域名?

【问题讨论】:

    标签: python html scrapy


    【解决方案1】:

    你可以从response.urlextract the domain name:

    from urlparse import urlparse
    
    def parse(self, response):
        parsed_uri = urlparse(response.url)
        domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
        print domain
    

    【讨论】:

      【解决方案2】:

      对于 Python3,'from' 和 'print' 的两个非常小的变化。 alecxe 的回答对 Python2 有好处。

      另外,对于 Scrapy 的 CrawlSpider,将上面的名称 'parse' 更改为其他名称,因为 CrawlSpider 自己使用 'parse'。

      from urllib.parse import urlparse
      
      def get_domain(self, response):
          parsed_uri = urlparse(response.url)
          domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
          print(domain)
          return domain
      

      那你就可以用它了,作为OP的例子

      x = get_domain
      

      或者就我而言,我想将域传递给 Scrapy 的 CrawlSpider 的 Rule 的 LinkExtractor 的 allow_domains。呸。这会将爬网限制到该域。

      rules = [ 
          Rule( 
              LinkExtractor( 
                  canonicalize=True, 
                  unique=True,
                  strip=True,
                  allow_domains=(domain)
              ), 
              follow=True, 
              callback="someparser" 
          ) 
      ]  
      

      【讨论】:

        【解决方案3】:

        试试:

        _rl = response.url
        url = _rl.split("/")[2]
        
        print (url)
        

        【讨论】:

          猜你喜欢
          • 2018-12-28
          • 1970-01-01
          • 2012-01-05
          • 2014-08-22
          • 2023-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多