with open('Price.csv', 'w', newline = '', encoding= 'utf-8') as csvFile:
csvWriter = csv.writer(csvFile, delimiter=' ')
csvWriter.writerow("Price")
for item in items:
whole_price = item.find_elements(By.XPATH, './/span[@]')
fraction_price = item.find_elements(By.XPATH, './/span[@]')
if whole_price != [] and fraction_price != []:
price = '.'.join([whole_price[0].text, fraction_price[0].text])
product_price.append(price)
else:
price = 0
csvWriter.writerow(product_price)
driver.quit()
試圖弄清楚如何將 price 附加到 product_price 并在末尾添加一個換行符。
這是我的結果,我很困惑為什么。我是否需要單獨列印行并添加新行。我以為 writerow 已經添加了一個新的換行符?
P r i c e
41.18 48.56 18.73 48.56 48.56 37.46 37.46 53.22 60.99 32.99 18.73 7.79 32.34 39.99 20.49 7.79 34.90 37.25 56.49 48.56 156.00 42.95 85.00 34.98 60.00 17.98 60.61 95.50 6.59 7.49 87.40 74.00 17.73 52.56 34.99 39.99 170.00 18.73 2.
uj5u.com熱心網友回復:
writerowwithout sat the end 用于在一行中寫入串列中的所有值。
而且您在一個串列中擁有所有值 - 因此它將其視為單行。
當您找到價格時,您應該直接寫行 - 但price必須作為串列。
price = '.'.join([whole_price[0].text, fraction_price[0].text])
csvWriter.writerow( [price] )
或者您應該附加price為具有單個值的串列
price = '.'.join([whole_price[0].text, fraction_price[0].text])
product_price.append( [price] )
然后在最后使用writerowswiths將每個嵌套串列寫為單獨的行
csvWriter.writerows(product_price) # with `s` at the end
順便說一句:當您撰寫標題時,您還應該使用串列
csvWriter.writerow( ["Price"] )
因為此時它"Price"作為字串列
csvWriter.writerow( ["P", "r", "i", "c", "e"] )
它在字符之間寫入空格。
編輯:
# PEP8: `lower_case_names` for variables `csv_file`, `csv_writer`
with open('Price.csv', 'w', newline='', encoding='utf-8') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=' ')
csv_writer.writerow( ["Price"] )
for item in items:
whole_price = item.find_elements(By.XPATH, './/span[@]')
fraction_price = item.find_elements(By.XPATH, './/span[@]')
if whole_price and fraction_price:
price = '.'.join([whole_price[0].text, fraction_price[0].text])
csv_writer.writerow( [price] )
PEP 8——Python 代碼風格指南
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479401.html
