web-scraping - 如何从scrapy中替换或删除特殊字符?
问题描述
我刚开始学习scrapy并试图让蜘蛛从网站上获取一些信息并尝试替换或删除“short_descr”中的特殊字符
import scrapy
class TravelspudSpider(scrapy.Spider):
name = 'travelSpud'
allowed_domains = ['www.tripadvisor.ca']
start_urls = [
'https://www.tripadvisor.ca/Attractions-g294265-Activities-c57-Singapore.html/'
]
base_url = 'https://www.tripadvisor.ca'
def parse(self, response, **kwargs):
for items in response.xpath('//div[@class= "_19L437XW _1qhi5DVB CO7bjfl5"]'):
yield {
'name': items.xpath('.//span/div[@class= "_1gpq3zsA _1zP41Z7X"]/text()').extract()[1],
'reviews': items.xpath('.//span[@class= "DrjyGw-P _26S7gyB4 _14_buatE _1dimhEoy"]/text()').extract(),
'rating': items.xpath('.//a/div[@class= "zTTYS8QR"]/svg/@title').extract(),
'short_descr': items.xpath('.//div[@class= "_3W_31Rvp _1nUIPWja _17LAEUXp _2b3s5IMB"]'
'/div[@class="DrjyGw-P _26S7gyB4 _3SccQt-T"]/text()').extract(),
'place': items.xpath('.//div[@class= "ZtPwio2G"]'
'/div'
'/div[@class= "DrjyGw-P _26S7gyB4 _3SccQt-T"]/text()').extract(),
'cost': items.xpath('.//div[@class= "DrjyGw-P _26S7gyB4 _3SccQt-T"]'
'/div[@class= "DrjyGw-P _1SRa-qNz _2AAjjcx8"]'
'/text()').extract(),
}
next_page_partial_url = response.css("div._1I73Kb0a").css("div._3djM0GaD").xpath('.//a/@href').extract_first()
if next_page_partial_url is not None:
next_page_url = self.base_url + next_page_partial_url
yield scrapy.Request(next_page_url, callback=self.parse)
我要替换的字符是Hiking Trails • Scenic Walking Areas
. 中间的点在 csv 文件中解码,因为•
Everyting else 就像一个魅力。
我尝试使用.replace()
,但出现错误:
AttributeError: 'list' object has no attribute 'replace'
任何帮助,将不胜感激
解决方案
如果您删除这些特殊字符只是因为它们在 CSV 文件中奇怪地出现,那么我建议不要删除它们。只需在settings.py
文件中添加以下行。
FEED_EXPORT_ENCODING = 'utf-8-sig'
这将打印 CSV 文件中的特殊字符。
推荐阅读
- mongodb - 具有预排序和限制的mongodb聚合
- xamarin - Xamarin 下载文件到 - 路径访问被拒绝
- scripting - 无法从用 Tcl 编写的应用程序中找到包
- c++ - 迭代在 cicle C++ 期间改变大小的无序集
- javascript - 在 add_action WooCommerce 中运行 JS 函数
- validation - Kotlin 数据类和 Bean 验证:Double 字段上的 @NotNull 不起作用
- python - 将列表设置为字典值会导致 TypeError: unhashable type: 'list'
- django - 如何建立一个 django 模型来存储 twitter 对话?
- django - Python MongoDB ReferenceError:弱引用对象不再存在
- javascript - 为什么在函数中重新声明标识符会屏蔽同名参数?