我写了一个蜘蛛,它会返回我的数据,里面散落着空格和换行符。换行符还导致extract()方法作为列表返回。我如何过滤这些在接触选择器之前?在extract()被调用之后对这些数据进行过滤打破了枯燥原则,因为我需要从一个页面中提取大量数据,即无属性,这使得解析它的唯一方法是通过索引。
我怎么过滤这些?
它返回像这样的坏数据
{ 'aired': ['\n ', '\n Apr 3, 2016 to Jun 26, 2016\n '],
'broadcast': [], 'duration': ['\n ', '\n 24 min. per ep.\n '], 'episodes': ['\n ', '\n 13\n '], 'favourites': ['\n ', '\n 22,673\n'], 'genres': ['Action', 'Comedy', 'School', 'Shounen', 'Super Power'], 'image_url': ['https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg',
'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg'], 'licensors': ['Funimation'], 'members': ['\n ', '\n 818,644\n'], 'popularity': ['\n ', '\n #21\n'], 'premiered': ['Spring 2016'], 'producers': ['Dentsu',
'Mainichi Broadcasting System',
'Movic',
'TOHO animation',
'Shueisha'], 'ranked': ['\n ', '\n #135', '\n ', '\n'], 'rating': ['\n ', '\n PG-13 - Teens 13 or older\n '], 'score': ['8.44'], 'source': ['\n ', '\n Manga\n '], 'status': ['\n ', '\n Finished Airing\n '], 'studios': ['Bones'], 'title': 'Boku no Hero Academia', 'type': ['TV']}编辑:指向源代码的链接与发布的时间不同,要查看代码,然后查看提交faae4aff1f998f5589fab1616d21c7afc69e03eb
发布于 2018-08-14 17:06:17
查看您的代码,您可以尝试使用xpath规范化空间。
mal_item['aired'] = border_class.xpath('normalize-space(.//div[11]/text())').extract()
*未经检验,但似乎是合法的。
对于一个更普遍的答案,yourString.strip('someChar')或yourString.replace('this','withThis')工作得很好(但在使用json对象操作的情况下,它可能没有其他方法那么有效)。如果原始数据中存在这些字符,则需要手动删除或跳过它们。
发布于 2018-08-14 17:50:18
换行符还导致extract()方法作为列表返回。
造成这种行为的不是中断行,而是节点在文档树中的出现方式。由元素节点(例如,<a>, <br>, <hr> )分隔的文本节点被看作是单独的实体,而such将产生这些实体(实际上,即使只选择了一个节点,extract()也应该总是返回一个列表)。XPath有几个基本的值处理/过滤功能,但是它非常有限。
在提取()之后过滤这些内容被称为破坏干原理
您似乎确信,筛选这些输出的唯一正确方法是在选择器表达式中进行筛选。但是,对这些原则这么严格是没有用的,您是从目标节点中选择文本节点,这些节点必然会有过多的空白,或者分散在它们的容器周围。按内容进行XPath过滤非常缓慢,因此应该在其之外进行。后处理刮除字段是一种常见的做法。您可能想读一读关于刮伤装载机和处理器的文章。
否则,最简单的方法是:
# import re
...
def join_clean(texts):
return re.sub(r'\s+', ' ', ' '.join(texts)).strip()
...
mal_item['type'] = join_clean(border_class.xpath('.//div[8]/a/text()').extract())https://stackoverflow.com/questions/51846013
复制相似问题