如何删除[u'\n\n\n result here \n\n\n']并获得仅作为[u'result here']的结果...我正在使用scrapy
def parse_items(self, response):
str = ""
hxs = HtmlXPathSelector(response)
for titles in titles:
item = CraigslistSampleItem()
item ["job_id"] = (id.select('text()').extract() #ok
items.append(item)
return(items)
end有谁可以帮我?
发布于 2013-08-28 14:14:46
id.select('text()').extract() 返回包含文本的字符串列表。您应该遍历该列表以剥离每个项目,或者使用切片(例如your_list.strip() )来执行剥离空白。Strip方法实际上与字符串数据类型相关联。
def parse_items(self, response):
str = ""
hxs = HtmlXPathSelector(response)
for titles in titles:
item = CraigslistSampleItem()
item ["job_id"] = id.select('text()').extract()[0].strip() #this should work if #there is some string data available. otherwise it will give an index out of range error.
items.append(item)
return(items)
end发布于 2013-08-28 15:42:59
使用Python的 .strip()的替代方案
您可以在选择“job_id”的XPath表达式周围使用XPath函数normalize-space():
def parse_items(self, response):
hxs = HtmlXPathSelector(response)
for titles in titles:
item = CraigslistSampleItem()
item ["job_id"] = title.select('normalize-space(.//td[@scope="row"])').extract()[0].strip()
items.append(item)
return(items)注意1:我使用的XPath表达式是基于https://careers-cooperhealth.icims.com/jobs/search?ss=1&searchLocation=&searchCategory=&hashed=0的
备注2在答案中使用 .strip(): id.select('text()').extract()[0].strip()会得到u'result here',而不是列表。
这可能正是您所需要的,但是如果您想保留列表,因为您要求删除[u'\n\n\n result here \n\n\n']并获得[u'result here']形式的结果,那么您可以使用如下所示的内容,使用Python的map()
item ["job_id"] = map(unicode.strip, id.select('text()').extract())https://stackoverflow.com/questions/18480363
复制相似问题