Python 2.7 Scrapy请求URL出错

Python 2.7 Scrapy请求URL出错,python-2.7,url,scrapy,scrapy-spider,Python 2.7,Url,Scrapy,Scrapy Spider,我正在使用Scrapy来爬网一个站点 我的问题是,当我从href中提取url时,我在url中得到了%20。所以,为了删除它,我使用了split并得到了我想要的url 例如: 原始URL: 我修改的URL如下所示: 所以我将修改后的url提供给Request方法,但Request方法仍然使用原始url,而不是修改后的url 下面是我的解析和提取方法 def parse(self, response): sel = Selector(response) requests = []

我正在使用Scrapy来爬网一个站点

我的问题是,当我从href中提取url时,我在url中得到了%20。所以,为了删除它,我使用了split并得到了我想要的url

例如:

原始URL:

我修改的URL如下所示:

所以我将修改后的url提供给Request方法,但Request方法仍然使用原始url,而不是修改后的url

下面是我的解析和提取方法

def parse(self, response):
    sel = Selector(response)
    requests = []

    # Get Product Reviews
    for url in sel.xpath('//div[contains(@id,"post")]/div/div[2]/h3/a/@href').extract():
        url = url.encode('utf-8').split('%')[0]
        requests.append(Request(url, callback=self.extract))

    for request in requests:
        print request.url
        yield request
        
def extract(self, response):
    sel = Selector(response)
    requestedItem = ProductItem()
    requestedItem['name'] = sel.xpath('//*[@id="content-wrapper"]/div/div[1]/div[1]/div/div/h1/text()').extract()[0].encode('utf-8')
    requestedItem['description'] = sel.xpath('//*[@id="content-wrapper"]/div/div[1]/div[2]/div/div/div[1]/p/text()').extract()[0].encode('utf-8')
    
    yield requestedItem

因此,请任何人帮助我解决这个问题

请看下面的答案和相关问题:

如您所见,URL中添加了空格。为此,您可以在选择URL时规范化空间,也可以在生成请求之前简单地去除空间

这是因为%20是一个单独的空间-只有当您调用URL时才会转义,而您在URL的末尾看不到%20

因此,与其使用

url = url.encode('utf-8').split('%')[0]
你也可以

for url in sel.xpath('normalize-space(//div[contains(@id,"post")]/div/div[2]/h3/a/@href)').extract():
    requests.append(Request(url, callback=self.extract))


你能粘贴你在Scrasty中得到的错误吗?我没有得到任何错误,但当我在请求中尝试我的原始url时,它将重定向到默认页面,因此我想删除错误的功能,并重定向到修改的url。修改的url末尾将有一个空格。你的url已被清除。在给出请求之前,通过print reponse.url说服自己。也许你有其他的行为,我需要更多的细节。@SergiuZaharie我仍然遇到同样的问题,请检查我编辑的问题
for url in sel.xpath('//div[contains(@id,"post")]/div/div[2]/h3/a/@href').extract():
    requests.append(Request(url.strip(), callback=self.extract))