Python 尝试刮取以下网站时csv文件中的格式问题
我正试图抓取一个网站以获取标题和价格,但一旦数据被提取并保存在csv文件中,价格列格式就会受到干扰,并且无法正确显示在列中,例如8900美元在一列中变为8美元,900美元移到下一列。Python 尝试刮取以下网站时csv文件中的格式问题,python,selenium,csv,web-scraping,export-to-csv,Python,Selenium,Csv,Web Scraping,Export To Csv,我正试图抓取一个网站以获取标题和价格,但一旦数据被提取并保存在csv文件中,价格列格式就会受到干扰,并且无法正确显示在列中,例如8900美元在一列中变为8美元,900美元移到下一列。 from selenium import webdriver import time max_pages = 1 driver = webdriver.Chrome() with open('autotrader.csv', 'w') as f: f.write("Title,Price \n&
from selenium import webdriver
import time
max_pages = 1
driver = webdriver.Chrome()
with open('autotrader.csv', 'w') as f:
f.write("Title,Price \n")
for i in range(1, max_pages + 1):
url = "https://www.autotrader.co.uk/car-search?advertClassification=standard&postcode=WC2N%205DU&onesearchad=Used&onesearchad=Nearly%20New&onesearchad=New&advertising-location=at_cars&is-quick-search=TRUE&include-delivery-option=on&page=" + str(max_pages)
driver.get(url)
title = driver.find_elements_by_xpath('//h3[@class="product-card-details__title"]')
price =driver.find_elements_by_xpath('//div[@class="product-card-pricing__price"]')
page_items = len(title)
with open('autotrader.csv', 'a') as f:
for i in range(page_items):
f.write(title[i].text + "," + price[i].text + "\n")
driver.close()
使用
csv.writer
,它将正确引用包含分隔符的字段:
import csv
# ... code to fetch titles and prices ...
with open('autotrader.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['Title','Price'])
for t,p in zip(title,price):
w.writerow([t.text,p.text])
CSV表示逗号分隔的值。使用
|
(pipe)字符分隔列,即f.write(title[i].text+“|”+price[i].text+“\n”)
。祝你好运。你也可以引用所有的entries@pcalkins我不understand@shellter它没有解决我的问题,不幸的是,一半的价格现在是附加标题如果你只是引用你的所有条目,那么你可以包括分隔符,如果它是数据的一部分。。。(使用双引号…然后确保过滤掉任何传入的双引号…尽管我认为您会得到“”。)