2016-06-24 1 views
3

현재 기사 가격으로 웹 사이트를 긁어 내려고했지만 문제가 발생했습니다 (가격이 동적으로 생성 된 후 큰 문제가 발생 했음).).치료에서 깨지 않는 공간 제거/제외

가격 및 기사 이름을 문제없이받을 수 있지만 '가격'의 모든 두 번째 결과는 '\ xa0'입니다. 나는 'normalize-space()'를 사용하여 제거하려고했지만 아무 소용이 없다.

내 코드 :

import scrapy 
from scrapy import signals 
from scrapy.http import TextResponse 
from scrapy.xlib.pydispatch import dispatcher 
from horni.items import HorniItem 

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.wait import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
import time 
from selenium.webdriver.common.keys import Keys 

class mySpider(scrapy.Spider): 
    name = "placeholder" 
    allowed_domains = ["placeholder.com"] 
    start_urls = ["https://www.placeholder.com"] 

    def __init__(self): 
     self.driver = webdriver.Chrome() 
     dispatcher.connect(self.spider_closed, signals.spider_closed) 

    def spider_closed(self, spider): 
     self.driver.close() 

    def parse(self, response): 
     self.driver.get("https://www.placeholder.com") 
     response = TextResponse(url=self.driver.current_url, body=self.driver.page_source, encoding='utf-8') 
     for post in response.xpath('//body'): 
      item = myItem() 
      item['article_name'] = post.xpath('//a[@class="title-link"]/span/text()').extract() 
      item['price'] = post.xpath('//p[@class="display-price"]/span]/text()').extract() 
      yield item 
+0

관심이 있으시면 http://stackoverflow.com/a/33829869/2572383에서 다양한 여백 문자와 XPath'normalize-space()'및/또는 Python의' strip()' –

+0

'/ p [@ class = "display-price"]/span]/text()'를 적용 할 수있는 HTML 스 니펫을 보여줄 수 있습니까? –

답변

3

\xa0은 라틴어의 비 분리 공간입니다.

string = string.replace(u'\xa0', u' ') 

업데이트 :

당신은 다음과 같은 코드를 적용 할 수 있습니다 이런 식으로 교체 여기에서

for post in response.xpath('//body'): 
    item = myItem() 
    item['article_name'] = post.xpath('//a[@class="title-link"]/span/text()').extract() 
    item['price'] = post.xpath('//p[@class="display-price"]/span]/text()').extract() 
    item['price'] = item['price'].replace(u'\xa0', u' ') 
    if(item['price'].strip()): 
     yield item 

당신이 문자를 교체하고 가격 경우 만 항목을 얻을 비어 있지 않습니다.

+0

답장을 보내 주셔서 감사합니다. 그러나, 나는 이것을 어떻게하는지 이해할 수 없다. 내 item [ 'price']'에 코드를 적용 할 수 있습니까? 아니면 비공개 공간을 치료 반응에서 모두 제외시키는 방법이 있습니까? – rongon

+0

귀하의 의견에 관한 제 답변을 업데이트했습니다. – cb0

+0

도움 주셔서 감사합니다. 'if (item [ 'price']. strip()) :'요소가 목록이므로 나를 위해 작동하지 않았습니다. 그러나 당신은 올바른 방향으로 나를 밀어 냈습니다. x! = u '\ xa0''이라면 item ['prices ']에서 x에 대해 x를 사용했습니다. – rongon

관련 문제