将基础网址与scrapy中产生的href相结合

Shi*_*dla 9 python url scrapy

下面是我的蜘蛛代码,

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,'------->'
Run Code Online (Sandbox Code Playgroud)

在这里我试图将href链接与基本链接组合,但我收到以下错误,

exceptions.ValueError: Missing scheme in request url: www.domain.com//bookstore/detail/3271993?alt=Something+I+Had+To+Do
Run Code Online (Sandbox Code Playgroud)

任何人都可以让我知道为什么我收到此错误以及如何加入基本网址与href链接并产生一个请求

Sja*_*aak 13

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

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

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


GHa*_*jba 8

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

response.urljoin(i[1:])
Run Code Online (Sandbox Code Playgroud)

这个解决方案更进一步:Scrapy在这里加入了域名基础.正如您所看到的,您不必提供明显http://www.example.com的加入.

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