Scrapy Request URL 出错

Scrapy Request URL going wrong

我正在使用 Scrapy 抓取网站

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

例如:

Original URL : http://www.example.com/category/%20

My modified URL looks like : http://www.example.com/category/

所以我将修改后的 url 提供给 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

所以,请任何人帮助我解决这个问题

请查看以下答案(及相关问题):

如您所见,白色 space 已添加到 URL。为此,您可以 normalize-space 当您 select URL 或简单地 strip 在您屈服请求之前。

那是因为 %20 是一个单独的 space -- 只有当您调用 URL 并且您在 URL.

所以不用

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))

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