Skip to main content
 首页 » 编程设计

python之如何删除 scrapy 输出中的逗号

2024年10月24日10telwanggs

我正在研究一个 scrapy 蜘蛛。这是我的代码:

item = MyItem() 
item['Description'] = response.xpath('//*[@id="textepresentation"]//p').extract() 
item['Description'] = [ '\,'.join(field.split(',')) for field in item.get('Description', [])] 

我得到这个结果:

 [ u'<p>Some text.</p>', 
             u'<p>\xa0</p>', 
             u'<p>\xa0</p>', 
             u'<p>\xa0</p>', 
  u'<p>Some other text.</p>', 
              u'<p>\xa0</p>', 
              u'<p>\xa0</p>'], 

我想删除空的 <p> </p>标签:

item['Description'] = [ ''.join(field.replace('<p>'u'\xa0''</p>', '').encode('utf-8')) for field in item.get('Description', [])] 

我得到了这个结果:

['<p>Some text.</p>', 
             '', 
             '', 
             '', 
 '<p>Some other text.</p>', 
             '', 
             ''], 

现在,我怎样才能删除结果中的逗号才能得到这个?

['<p>Some text.</p>' 
 '<p>Some other text</p>'] 

请您参考如下方法:

您需要获取 text() 并调用 extract_first():

response.xpath('//*[@id="textepresentation"]//p/text()').extract_first()