Python 在scrapy响应中去除不需要的字符
我正在用Scrapy 1.0.3编写一个spider,它将抓取Unicode页面的存档,并在页面的p标记中生成文本,然后将其转储到JSON文件中。我的代码如下所示:Python 在scrapy响应中去除不需要的字符,python,xpath,scrapy,Python,Xpath,Scrapy,我正在用Scrapy 1.0.3编写一个spider,它将抓取Unicode页面的存档,并在页面的p标记中生成文本,然后将其转储到JSON文件中。我的代码如下所示: def parse(self,response): sel = Selector(response) list=response.xpath('//p[@class="articletext"]/font').extract() list0=response.xpath('//p[@class="titl
def parse(self,response):
sel = Selector(response)
list=response.xpath('//p[@class="articletext"]/font').extract()
list0=response.xpath('//p[@class="titletext"]').extract()
string = ''.join(list).encode('utf-8').strip('\r\t\n')
string0 = ''.join(list0).encode('utf-8').strip('\r\t\n')
fullstring = string0 + string
stringjson=json.dumps(fullstring)
with open('output.json', 'w') as f:
f.write(stringjson)
try:
json.loads(stringjson)
print("Valid JSON")
except ValueError:
print("Not valid JSON")
但是,我得到了不需要的/r/t/n字符序列,尽管使用了split(),但无法删除这些字符。为什么它不起作用?我该如何让它起作用?你说的“无法删除”是什么意思?您是否已经有包含内容的字符串?
移除它们相当容易:
str = "Test\r\n\twhatever\r\n\t"
str = str.replace("\r", '')
str = str.replace("\n", '')
str = str.replace("\t", '')
“无法删除”是什么意思?您是否已经有包含内容的字符串?
移除它们相当容易:
str = "Test\r\n\twhatever\r\n\t"
str = str.replace("\r", '')
str = str.replace("\n", '')
str = str.replace("\t", '')
在Python中,您需要使用多种方法中的任何一种来从字符串中删除字符
strip()
仅删除开头和结尾的空白。使用与您已经在做的事情类似的方法:
string = ''.join(c for c in list if c not in '\r\t\n')
string0 = ''.join(c for c in list0 if c not in '\r\t\n')
您也可以在执行此操作之前将string
和string0
添加到一起,这样您只需执行一次
编辑(回复评论):
在Python中,您需要使用多种方法中的任何一种来从字符串中删除字符
strip()
仅删除开头和结尾的空白。使用与您已经在做的事情类似的方法:
string = ''.join(c for c in list if c not in '\r\t\n')
string0 = ''.join(c for c in list0 if c not in '\r\t\n')
您也可以在执行此操作之前将string
和string0
添加到一起,这样您只需执行一次
编辑(回复评论):
替代解决方案:xpath的“规范化空间”函数
例如:
list=response.xpath('normalize-space(//p[@class="articletext"]/font)').extract()
而不是
list=response.xpath('//p[@class="articletext"]/font').extract()
normalize space函数从字符串中去掉前导和尾随空格,用单个空格替换空格字符序列,并返回结果字符串。替代解决方案:xpath的“normalize space”函数
例如:
list=response.xpath('normalize-space(//p[@class="articletext"]/font)').extract()
而不是
list=response.xpath('//p[@class="articletext"]/font').extract()
normalize space函数从字符串中去除前导和尾随空格,用单个空格替换空格字符序列,并返回结果字符串。在哪里使用
split()
?我想您的意思是strip()
,但是,strip()
将只删除前导字符和尾随字符,而不删除字符串中的字符。或者您的意思是在当前使用strip()
的地方使用split()
?我想你的意思是strip()
,但是,strip()
将只删除前导字符和尾随字符,而不删除字符串中的字符。或者你的意思是在当前使用strip()
的地方使用split()
,这对单个字符有效,但我仍然得到“\r\n\r\n”的序列,“\r\n\t”之类的。这对单个字符有效,但我仍然会得到“\r\n\r\n”、“r\n\t”之类的序列。此方法仍然会给我留下一些不需要的序列,需要消除它们,例如“\r\n\t”、“r\n”等等。您尝试过吗?这将删除所有有问题的字符。请参阅我的编辑。此方法仍然会给我留下一些不需要的序列,需要消除这些序列,如“\r\n\t”和“\r\n”等等。您尝试过吗?这将删除所有有问题的字符。请参阅我的编辑。