【发布时间】:2014-12-07 12:51:11
【问题描述】:
我有从 this 网站上抓取的国家/地区列表,其值类似于
(注意:这是all_countries在迭代其元素后的输出)
<a data-flexible="" SELECT data-id="AU" href="http://www.wotif.com/AU">Australia</a>
<a data-flexible="" data-id="NZ" href="http://www.wotif.com/NZ">New Zealand</a>
<a data-flexible="" data-id="ID" href="http://www.wotif.com/ID">Indonesia</a>
<a data-flexible="" data-id="TH" href="http://www.wotif.com/TH">Thailand</a>
<a data-flexible="" data-id="SG" href="http://www.wotif.com/SG">Singapore</a>
<a data-flexible="" data-id="GB" href="http://www.wotif.com/GB">United Kingdom</a>
<a data-flexible="" data-id="TH" href="http://www.wotif.com/TH">Thailand</a>
<a data-flexible="" data-id="AU" href="http://www.wotif.com/AU">Australia</a>
<a data-flexible="" data-id="AR" href="http://www.wotif.com/AR">Argentina</a>
<a data-flexible="" data-id="NZ" href="http://www.wotif.com/NZ">New Zealand</a>
我想做的是获得唯一独特的国家
这是我尝试过的。
all_countries = countries.select('div#country-box ul li a')
for index,value in enumerate(all_countries):
print(value)
all_countries[index] = value.text
all_countries = set(all_countries)
all_countries = list(all_countries)
for index,value in enumerate(all_countries):
print(value)
嗯,好吧,我现在有独特的元素,但它不保持这些国家的顺序,因为它们出现在 MultiSelectList 中,我还需要属性值 data-id 和 href 以及 a 的文本标记供以后在我的脚本中使用。
如果我这样做了
all_countries = countries.select('div#country-box ul li a')
all_countries = set(all_countries)
all_countries = list(all_countries)
这是一个好方法吗?
【问题讨论】:
-
预期输出是什么?
-
所以我得到了基于
data-id值的唯一元素 -
@falsetru 如果我这样做
all_countries = list(collections.OrderedDict.fromkeys(all_countries)),那么我将拥有澳大利亚 2 次,因为它的标记不同。这就是为什么我想根据data-id值获得独一无二的原因 -
看看我的回答。
标签: python python-3.x beautifulsoup