【发布时间】:2017-04-19 22:47:49
【问题描述】:
我创建了一个蜘蛛,它按照我的预期收集数据。我现在面临的唯一问题是结果有很多重复。但是,我想在 csv 中写入结果时去掉重复项:
代码如下:
import csv
import requests
from lxml import html
def Startpoint():
global writer
outfile=open('Data.csv','w',newline='')
writer=csv.writer(outfile)
writer.writerow(["Name","Price"])
address = "https://www.sephora.ae/en/stores/"
page = requests.get(address)
tree = html.fromstring(page.text)
titles=tree.xpath('//li[contains(@class,"level0")]')
for title in titles:
href = title.xpath('.//a[contains(@class,"level0")]/@href')[0]
Layer2(href)
def Layer2(address):
global writer
page = requests.get(address)
tree = html.fromstring(page.text)
titles=tree.xpath('//li[contains(@class,"amshopby-cat")]')
for title in titles:
href = title.xpath('.//a/@href')[0]
Endpoint(href)
def Endpoint(address):
global writer
page = requests.get(address)
tree = html.fromstring(page.text)
titles=tree.xpath('//div[@class="product-info"]')
for title in titles:
Name = title.xpath('.//div[contains(@class,"h3")]/a[@title]/text()')[0]
Price = title.xpath('.//span[@class="price"]/text()')[0]
metco=(Name,Price)
print(metco)
writer.writerow(metco)
Startpoint()
【问题讨论】:
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。
标签: python csv web-crawler