python - Python for循环简单数组

标签 python arrays loops xpath selenium-webdriver

嗨,我有以下代码:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://groceries.asda.com/asda-webstore/landing/home.shtml?cmpid=ahc--ghs-d1--asdacom-dsk-_-hp#/shelf/1215337195041/1/so_false')

products = []

div = driver.find_element_by_id('listings')

product_title = driver.find_elements_by_xpath('//div[@id="listings"]//a[@title]')
product_price = driver.find_elements_by_xpath('//div[@id="listings"]//span[@class="price"]/span')
product_wasprice = driver.find_elements_by_xpath('//strike[@class="wasprice"]')
product_weight = driver.find_elements_by_xpath('//p[@class="subTitle"]')

products = [product_title, product_weight, product_wasprice, product_weight]

for item in product_title:
    print item.text.strip()

driver.close()


当前,它打印出product_title中出现的所有项目。

我想使用定义为products的数组,以便创建具有通过products迭代的所有值的输出csv文件。

所以目前我的输出如下:

product1,
product2,
etc...


我想:

product_title1, product_weight1, product_wasprice1, product_weight1
product_title2, product_weight2, product_wasprice2, product_weight2


我想这只是知道如何定义遍历所有数组元素的for循环。

提前致谢!

最佳答案

您似乎正在寻找zip function或更高效的表亲itertools.izip。这些结合了可迭代的对象,因此您可以同时遍历它们。

from itertools import izip
products = izip(product_title, product_price, product_wasprice, product_weight)

for row in products:
    print ", ".join(item.text.strip() for item in row)


使用上面的示例,每个row将是一个元组,其中包含传递到zip的每个列表中的一个元素。如果需要使用此数据做进一步的计算,则还可以在for中使用逗号分隔的变量来扩展这些元组。

for title, price, wasprice, weight in products:
    pass # your code here

关于python - Python for循环简单数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486758/

相关文章:

python - 几个大嵌套循环的小循环 vs 小嵌套循环的大循环性能?

Python线程转储

java - 如何在java中显示正确的数组

css - 带有 $count 的 Div 类名;在 wordpress 循环中

php - 字符串作为数组

C++ 使用 RAII 创建数组

r - 有没有办法将更大列表中的数据帧列表汇总在一起?

python - 通过列表中的索引将一个字符替换为另一个字符

python - Pandas 字典到数据框 - 列乱序?

python - 如何创建包含所有相关文本的单个列?