在 运行 scrapy for python 的 for 循环中检查 xpath 重复项
Check for xpath duplicates while running a for loop in scrapy for python
我正在通过 scrapy 抓取 xml 数据,同时我想检查重复项。为此,我使用以下代码:
arr = []
for tr in response.xpath('/html/body/table[1]'):
if tr.xpath('tr/td/text()').extract() not in arr:
arr.append(tr.xpath('tr/td/text()').extract())
print arr
这会产生以下输出(演示数据):
[[u'test1', u'12', u'test2', u'12', u'test1', u'12', u'test2', u'12']]
但我想要以下输出:
[[test1, 12, test2, 12]]
所以,我想去掉重复项。谁能告诉我我做错了什么?
提前发送
试试:
list(
chain(
*list(
{ e : 1 for e in list(zip_longest(*([iter(tr)] * 2), fillvalue=''))}.keys()
)))
它在重复的同一个列表上创建了一个可迭代对象,因此它混合了两者的元素。然后我使用字典理解来删除从 zip_longest()
生成的重复元组。 chain
扁平化元组内的值,list()
耗尽可迭代对象。
我确实模拟了你的 xpath
命令的结果,因为你没有提供完整的有效示例。
from itertools import zip_longest, chain
#tr = response.xpath('/html/body/table[1]')
tr = ['test1', '12', 'test2', '12', 'test1', '12', 'test2', '12']
l = list(
chain(
*list(
{ e : 1 for e in list(zip_longest(*([iter(tr)] * 2), fillvalue=''))}.keys()
)))
print(l)
它产生:
['test2', '12', 'test1', '12']
我正在通过 scrapy 抓取 xml 数据,同时我想检查重复项。为此,我使用以下代码:
arr = []
for tr in response.xpath('/html/body/table[1]'):
if tr.xpath('tr/td/text()').extract() not in arr:
arr.append(tr.xpath('tr/td/text()').extract())
print arr
这会产生以下输出(演示数据):
[[u'test1', u'12', u'test2', u'12', u'test1', u'12', u'test2', u'12']]
但我想要以下输出:
[[test1, 12, test2, 12]]
所以,我想去掉重复项。谁能告诉我我做错了什么?
提前发送
试试:
list(
chain(
*list(
{ e : 1 for e in list(zip_longest(*([iter(tr)] * 2), fillvalue=''))}.keys()
)))
它在重复的同一个列表上创建了一个可迭代对象,因此它混合了两者的元素。然后我使用字典理解来删除从 zip_longest()
生成的重复元组。 chain
扁平化元组内的值,list()
耗尽可迭代对象。
我确实模拟了你的 xpath
命令的结果,因为你没有提供完整的有效示例。
from itertools import zip_longest, chain
#tr = response.xpath('/html/body/table[1]')
tr = ['test1', '12', 'test2', '12', 'test1', '12', 'test2', '12']
l = list(
chain(
*list(
{ e : 1 for e in list(zip_longest(*([iter(tr)] * 2), fillvalue=''))}.keys()
)))
print(l)
它产生:
['test2', '12', 'test1', '12']