附加到python列表

杰克·黄

我有一个网页抓取工具,可以像下面的示例一样返回值。

# Other code above here.
test = []

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")

    for each_item in product_feature.find_elements_by_tag_name('img'):
        zz = test.append(each_item.get_attribute('src')[34:-4])  # returning the values I want
        print(zz)

上面的代码将打印出如下结果:(我想要的是哪个值)

TCP_active
CI
DOH_active
TCP_active
CI
DOH
TCP
CI_active
DOH_active

我想获得以下结果:

[TCP_active, CI, DOH_active]
[TCP_active, CI, DOH]
[TCP, CI_active, DOH_active]

我应该怎么做?

我试过了:

test.append(each_item.get_attribute('src')[34:-4])

但这给了我:

[TCP_active]
[TCP_active, CI]
[TCP_active, CI, DOH_active]
[TCP_active, CI, DOH_active, TCP]
...

希望我的解释清楚

马丁·彼得斯(Martijn Pieters)

而不是print将您的结果附加到列表中;外循环的每次迭代都有一个新列表:

test = []

results = driver.find_elements_by_css_selector("li.result_content")
for result in results:
    # Other code about result.find_element_by_blah_blah
    product_feature = result.find_element_by_class_name("prod-feature-icon")
    features = [] 
    for each_item in product_feature.find_elements_by_tag_name('img'):
        features.append(each_item.get_attribute('src')[34:-4])
    test.append(features)

可以打印features,或者test,仅查看for循环的每个级别正在发生的情况

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章