Scrapy导出CSV出现多余空格,replace()无法去除如何解决?
问题解决:Scrapy抓取CSV出现多余空格的处理方法
核心问题
你用str.replace('\s+', ' ')是无效的——字符串的replace方法只匹配字面量字符串,不会把\s+当作正则表达式的“一个或多个空白字符”解析,自然无法去除连续的多余空格。
正确处理方式
1. 用正则替换连续空白
导入re模块后,使用re.sub(r'\s+', ' ', text)可以把所有连续空白(空格、换行、制表符等)替换成单个空格。
2. 先清首尾再理中间
配合strip()先去除文本首尾的空白,再处理中间的连续空格,结果更整洁。
3. 兜底处理空值
get()方法可能返回None,直接调用字符串方法会报错,需要用默认值或判断兜底。
修改后的代码示例
import re import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class DhqSpider(CrawlSpider): name = 'dhq1' allowed_domains = ['digitalhumanities.org'] start_urls = ['http://www.digitalhumanities.org/dhq/vol/16/3/index.html'] rules = ( Rule(LinkExtractor(allow = 'index.html')), Rule(LinkExtractor(allow = 'vol'), callback='parse_article'), ) def parse_article(self, response): # 处理标题:兜底空字符串,先清首尾再压缩中间空格 title_text = response.css('h1.articleTitle::text').get(default='') cleaned_title = re.sub(r'\s+', ' ', title_text.strip()) # 处理作者:逐个清理每个作者名的空白 cleaned_authors = [author.strip() for author in response.css('div.author a::text').getall()] # 处理出版信息:按索引提取后清理,避免索引越界 pub_info = response.css('div#pubInfo::text').getall() cleaned_year = re.sub(r'\s+', ' ', pub_info[0].strip()) if len(pub_info) > 0 else '' cleaned_volume = re.sub(r'\s+', ' ', pub_info[1].strip()) if len(pub_info) > 1 else '' # 处理XML链接:判断空值后拼接 xml_href = response.xpath('(//div[@class="toolbar"]/a[contains(@href, ".xml")]/@href)[1]').get() xmllink = response.urljoin(xml_href) if xml_href else '' yield { 'title' : cleaned_title, 'author1' : cleaned_authors, 'year' : cleaned_year, 'volume' : cleaned_volume, 'xmllink' : xmllink, }
额外说明
- 正则里的
r'\s+'是原始字符串,避免转义问题,能匹配任意类型的连续空白字符。 - 用
get(default='')替代直接get(),可以避免None调用字符串方法时抛出AttributeError。 - 对
getall()返回的列表用列表推导式处理,能确保每个作者名的格式统一。
内容的提问来源于stack exchange,提问作者David Beales
相关产品推荐
相关产品推荐

