我将每个产品的所有价格(price['value']
)保存在一行中,以逗号分隔。我需要做出哪些调整才能将每个价格保存在前一个价格下面的行中?
import mechanize
from lxml import html
import csv
import io
from time import sleep
def save_products (products, writer):
for product in products:
writer.writerow([ product["title"][0].encode('utf-8') ])
for price in product['prices']:
writer.writerow([x.encode('utf-8') for x in price['value']])
f_out = open('pcdResult.csv', 'wb')
writer = csv.writer(f_out)
links = ["http://purechemsdirect.com/ourprices.html/" ]
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
for link in links:
print(link)
r = br.open(link)
content = r.read()
products = []
tree = html.fromstring(content)
product_nodes = tree.xpath('//div[@class="col-md-6 col-lg-6 col-sm-12"]')
for product_node in product_nodes:
product = {}
try:
product['title'] = product_node.xpath('.//p/strong/text()')
except:
product['title'] = ""
price_nodes = product_node.xpath('.//ul')
product['prices'] = []
for price_node in price_nodes:
price = {}
try:
price['value'] = price_node.xpath('.//li/text()')
except:
price['value'] = ""
product['prices'].append(price)
products.append(product)
save_products(products, writer)
f_out.close()
答案 0 :(得分:0)
尝试在您的函数中使用此行:
writer.writerow([x.encode('utf-8') for x in price['value']])
把它变成:
for x in price['value']:
writer.writerow(x)