Skip to main content
 首页 » 编程设计

python之在 scrapy 响应中摆脱不需要的字符

2025年05月04日12zhenyulu

我在 Scrapy 1.0.3 中编写了一个蜘蛛程序,它将抓取 Unicode 页面的存档并在页面的 p 标签内生成文本并将其转储到 JSON 文件中。我的代码如下所示:

  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(),但我仍无法删除这些字符。为什么它不起作用?我该如何让它起作用?

请您参考如下方法:

您将希望使用多种方法中的任何一种从 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 添加在一起,这样您只需执行一次。

编辑(回复评论):

>>> test_string 
'This\r\n \tis\t\t \t\t\t(only) a \r\ntest. \r\n\r\n\r\nCarry\t \ton' 
>>> ''.join(c for c in test_string if c not in '\r\t\n') 
'This is (only) a test. Carry on'