Python将csv文件格式化为一行

时间:2016-05-18 12:24:35

标签: python csv

在从网站获取第一组文本后再使用逗号将cvs格式化为一行,然后是价格。我想要做的是在产品信息之后将产品信息和价格用逗号分隔,以便将其导入Excel电子表格。有线索吗?感谢

import requests
from bs4 import BeautifulSoup
import csv

b6 = open('sears.csv', 'w', newline='') 
a6 = csv.writer(b6,delimiter=',')

soup = BeautifulSoup(requests.get("http://www.sears.ca/catalog/appliances-fridges-freezers-refrigerators-top-freezer-en-wp-836#facet:&productBeginIndex:0&orderBy:&pageView:grid&minPrice:&maxPrice:&pageSize:100&").text)

g6_data = soup.select("div.product_name a")
p6_data = soup.select("div.product_price")

for g6, p6 in zip(g6_data, p6_data):
    c6 = (g6.text, p6.text)
    print(g6.text, p6.text)
    a6.writerow(c6)

b6.close()

1 个答案:

答案 0 :(得分:0)

您的请求没问题,过滤时BeautifulSoup没有。

import requests
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(requests.get("http://www.sears.ca/catalog/appliances-fridges-freezers-refrigerators-top-freezer-en-wp-836#facet:&productBeginIndex:0&orderBy:&pageView:grid&minPrice:&maxPrice:&pageSize:100&").text)

g_descrs = [i.find("a").text for i in soup.findAll("div", {"class": "product_name", "itemprop": True})]
g_prices = [i.find("input").get('value') for i in soup.findAll("div", {"class": "product_price"})]

rows = map(lambda x: '%s;%s' % x, zip(g_descrs, g_prices))

with open('./result.csv', 'w') as result:
    for row in rows:
        result.write(row)