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

标签 python xpath scrapy

我在 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')

您也可以在执行此操作之前将 stringstring0 添加在一起,这样您只需执行一次。

编辑(回复评论):

>>> 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'

关于python - 在 scrapy 响应中摆脱不需要的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177188/

相关文章:

python - 调度 Scrapy 蜘蛛以脚本的间隔运行

python - PySide:将标准输出重定向到对话框

XPATH 如何从同一父级中选择两个特定的子级

python - 在 Python 中使用 Selenium 单击并查看更多页面

python - Scrapy:没有标题的 CSV 输出

Python,抓取 : bad utf8 characters writed in file from scraped html page with charset iso-8859-1

python - 使用 python 进行多元线性回归

python - 你能向后迁移到南方第一次迁移之前吗?

python - 在多边形形状范围内剪切线形状文件

c# - 为什么这个 XPath 过滤器不起作用(最大数量)?