嗨,我有以下代码:
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/