如何將兩個單獨的for loop
數據放入CSV文件。第一列名稱是link
,第二列名稱是mobile_name
。如何將兩個單獨的for循環數據放入CSV文件
期待輸出:
result.csv
link,mobile_name
https://www.flipkart.com/moto-g5-plus-fine-gold-32-gb/p/itmes2zjvwfncxxr?pid=MOBEQHMGED7F9CZ2&srno=b_1_1&otracker=browse
&lid=LSTMOBEQHMGED7F9CZ2KHTBI8,Moto G5 Plus (Fine Gold, 32 GB)
代碼:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import time
chrome_path = r"C:\Users\Venkatesh\AppData\Local\Programs\Python\Python35\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
#driver.get("https://www.flipkart.com/mobiles")
driver.get("https://www.flipkart.com/mobiles")
search = driver.find_element_by_xpath("""//*[@id="container"]/div/div[2]/div/div[2]/div/div/div[1]/section/div[3]/div/div/a""").click()
delay = 90 # seconds
try:
#posts = WebDriverWait(driver, delay).until(EC.presence_of_element_located(driver.find_elements_by_class_name("iUmrbN")))
#posts = WebDriverWait(driver, delay).until(EC.presence_of_element_located(By.XPATH, "//*[@id='container']/div/div[2]/div/div[2]/div/div/div[1]/a/div[2]"))
#posts = driver.find_elements_by_class_name("iUmrbN")
#posts = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, "//*[@id='container']/div/div[2]/div/div[2]/div/div/div[1]/a/div[2]")))
WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, "//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div/div[1]/a/div[2]/div[1]/div[1]")))
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
print("Page is ready")
except TimeoutException:
print("Loading took too much time")
#print(driver.find_elements_by_class_name("_1UoZlX").get_attribute("href"))
time.sleep(10)
for post in driver.find_elements_by_class_name("_1UoZlX"):
link = post.get_attribute("href")
print(link)
for post1 in driver.find_elements_by_class_name("_3wU53n"):
mobile_name = post1.text
print(mobile_name)
修改後的代碼:
working fine
link = []
mobile_name = []
courses_list=[]
for post in driver.find_elements_by_class_name("_1UoZlX"):
link += [ post.get_attribute("href") ]
for post1 in driver.find_elements_by_class_name("_3wU53n"):
mobile_name += [ post1.text ]
link_mobile_name = []
for i in range(len(link)) :
link_mobile_name = [ link[i], mobile_name[i] ]
print(courses_list.append(link_mobile_name))
time.sleep(2)
driver.quit()
with open ('result.csv','w', newline='') as file:
writer=csv.writer(file)
writer.writerow(['product_link'])
for row in courses_list:
writer.writerow(row)
如果第一個列表中的項目與第二個列表中的項目匹配,您可以加入它們。 –
的內容會有所不同。我們怎樣才能加入一個鏈接另一個是文本?在上面只有兩個循環功能,它會更多5,在那一點上它會是複雜的權利?你能幫助我什麼是更好的方式來做到這一點。 –
我不是指數據類型,我的意思是它們之間的關係,例如:'link [0]'和'mobile_name [0]'反駁同樣的事情。如果是這樣,你可以創建第三個列表,如:[[link [0],mobile_name [0]],[link [1],mobile_name [1]]等]並使用它。 –