Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrapy error : exceptions.AttributeError: 'HtmlResponse' object has no attribute 'urljoin'

I have installed scrapy using pip and tried the example in the scrapy documentation.

I got the error cannot import name xmlrpc_client

After looking into a stachoverflow question here i have fixed it using

sudo pip uninstall scrapy

sudo pip install scrapy==0.24.2

but now it shows me exceptions.AttributeError: 'HtmlResponse' object has no attribute 'urljoin'

Here is my code :

import scrapy


class StackOverflowSpider(scrapy.Spider):
    name = 'stackoverflow'
    start_urls = ['https://stackoverflow.com/questions?sort=votes']

    def parse(self, response):
        for href in response.css('.question-summary h3 a::attr(href)'):
            full_url = response.urljoin(href.extract())
            yield scrapy.Request(full_url, callback=self.parse_question)

    def parse_question(self, response):
        yield {
            'title': response.css('h1 a::text').extract()[0],
            'votes': response.css('.question .vote-count-post::text').extract()[0],
            'body': response.css('.question .post-text').extract()[0],
            'tags': response.css('.question .post-tag::text').extract(),
            'link': response.url,
        }

Can anyone please help me with this!

like image 205
user3437315 Avatar asked Jun 30 '15 18:06

user3437315


1 Answers

In Scrapy >=0.24.2, HtmlResponse class does not yet have urljoin() method. Use urlparse.urljoin() directly:

full_url = urlparse.urljoin(response.url, href.extract())

Don't forget to import it:

import urlparse

Note that urljoin() alias/helper was added in Scrapy 1.0, here is the related issue:

  • Add Response.urljoin() helper

And here is what it actually is:

from six.moves.urllib.parse import urljoin

def urljoin(self, url):
    """Join this Response's url with a possible relative url to form an
    absolute interpretation of the latter."""
    return urljoin(self.url, url)
like image 77
alecxe Avatar answered Nov 14 '22 22:11

alecxe