【问题标题】:Scrapy replace() or strip() br/ tags from data从数据中抓取 replace() 或 strip() br/ 标签
【发布时间】:2021-10-13 01:04:30
【问题描述】:

我正在尝试使我抓取的文本数据看起来更干净,并删除 <br> 标记或将其替换为 csv 中的实际换行符:

<div>
  "This is an example."
   <br>
   "This is an example too."
<div>

当我使用 xpath 抓取文本并使用 strip() 函数 response.xpath('//div//text()').extract().strip()(我使用 itemloader,所以真正的函数看起来有点不同,但基本相同)时,输出如下所示:

['This is an example text.',
'',
'This is an example too.'],

#data in csv file:
"This is an example text.,This is an example too."

现在我要么想删除 &lt;br&gt; 标记,要么删除整个逗号,所以结果如下所示:"This is an example text. This is an example too"

或者我想用实际的换行符替换它:

"This is an example text. 
This is an example too."

我已经尝试了几个 .strip() 命令,即 .strip(u'\u0027') 删除引号或 .strip(u'\00A0') 删除空格,但没有任何效果

我真的可以用scrapy做到这一点吗?如果是的话,有什么想法吗?如果没有,我以后是否必须对 pandas 执行此操作?

【问题讨论】:

  • 我看到你已经得到了答案,不过这也可以用 response.xpath('string(//div)').get() 来完成,试试看。

标签: python html web-scraping scrapy


【解决方案1】:

试试:

response.xpath(''.join('//div//text()')).extract()

【讨论】:

  • 感谢这个成功的人(因为我使用了 ItemLoader 我必须使用“output_processor=Join(' ')”
【解决方案2】:

使用替换功能替换行尾的逗号

result = response.xpath('//div//text()').extract().strip().replace(",\n", "\n") 

【讨论】:

  • 这只会删除文本中的逗号 "this is ,an example" --> "this is an example"
  • @JarodSantoso,不,它用换行符替换逗号后跟换行符
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2018-02-12
  • 2014-11-18
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 2020-05-19
相关资源
最近更新 更多