【问题标题】:Combining base url with resultant href in scrapy在scrapy中将基本url与结果href结合起来
【发布时间】:2012-06-03 14:46:50
【问题描述】:

下面是我的蜘蛛代码,

class Blurb2Spider(BaseSpider):
   name = "blurb2"
   allowed_domains = ["www.domain.com"]

   def start_requests(self):
            yield self.make_requests_from_url("http://www.domain.com/bookstore/new")


   def parse(self, response):
       hxs = HtmlXPathSelector(response)
       urls = hxs.select('//div[@class="bookListingBookTitle"]/a/@href').extract()
       for i in urls:
           yield Request(urlparse.urljoin('www.domain.com/', i[1:]),callback=self.parse_url)


   def parse_url(self, response):
       hxs = HtmlXPathSelector(response)
       print response,'------->'

我在这里尝试将 href 链接与基本链接结合起来,但出现以下错误,

exceptions.ValueError: Missing scheme in request url: www.domain.com//bookstore/detail/3271993?alt=Something+I+Had+To+Do

谁能告诉我为什么会出现此错误以及如何使用 href 链接加入基本 url 并产生请求

【问题讨论】:

    标签: python url scrapy


    【解决方案1】:

    点击scrapy 中的链接的最佳方式是使用response.follow()。 scrapy 会处理剩下的事情。

    more info

    引用自文档:

    scrapy.Request 不同,response.follow 直接支持相对 URL - 无需调用 urljoin

    另外,您可以将<a> 元素直接作为参数传递。

    【讨论】:

      【解决方案2】:

      另一种解决方案,如果您不想使用urlparse

      response.urljoin(i[1:])
      

      这个解决方案更进一步:这里 Scrapy 计算出加入的域基础。如您所见,您无需提供明显的http://www.example.com 即可加入。

      如果您想更改正在抓取的域,这将使您的代码在将来可重用

      【讨论】:

      • 这比urlparse干净
      【解决方案3】:

      这是因为您没有添加方案,例如 http:// 在您的基本网址中。

      试试:urlparse.urljoin('http://www.domain.com/', i[1:])

      或者更简单:urlparse.urljoin(response.url, i[1:]) 因为 urlparse.urljoin 将自行整理基本 URL。

      【讨论】:

      • 非常感谢我得到了答案。
      • 同时你能告诉我 urlparse 和 urljoin 之间的区别,因为通过使用它们中的任何一个我都能得到答案
      • 方法 urlparse.urlparse 和 urlparse.urljoin 都是 urlparse 模块的一部分。另见:docs.python.org/library/urlparse.html
      • 您还在这里导入了什么?我运行类似的代码并得到错误 exceptions.NameError: global name 'Request' is not defined
      • 抱歉回复晚了,还没来得及登录。 @Mittenchops:from scrapy.http import Request
      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 2021-11-19
      • 2021-09-28
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多