在使用允许我从网站提取图像和测试的循环解决问题后,我遇到了另一个问题,当我尝试将提取的文本保存在 csv 文件的新行中时。
我正在做的是搜索一个带有“描述”类的 div,然后我选择我感兴趣的文本,打印数据(以检查一切是否正确),最后使用 writerow 提取数据(之前我打开文件并添加一行标题)。
编辑: 我的问题是它只保存了一行,即脚本搜索和提取的最后一行。我不知道我做错了什么。 我将把我拥有的两个函数放在脚本中:
main() 是我之前说过的地方。
def main(url, destino):
""" Acceso al sitio web """
soup = bs(urlopen(url), 'lxml')
parsed = list(urlparse.urlparse(url))
""" Acceso al archivo csv """
fileName = 'datos/datos.csv'
print fileName
f = csv.writer(open(fileName, 'w'))
f.writerow(["Lote", "Dato del lote", "Detalles"]) # Header
""" Acceso a la descr. y escritura en el csv """
description = soup.findAll(True, {'class':['description']})
for text in description:
loteNum = text.contents[1]
loteDat = text.contents[3]
detalle = text.contents[6]
detalleE = detalle.encode("utf-8")
print loteNum
print loteDat
print detalle
f.writerow([loteNum, loteDat, detalleE])
""" Descarga de las img. """
for image in soup.findAll(True, {'class':['list_logo']}):
print "Image: %(src)s" % image
image_url = urlparse.urljoin(url, image['src'])
filename = image["src"].split("/")[-1]
outpath = os.path.join(destino, filename)
urlretrieve(image_url, outpath)
getUrl() 允许我在我想要提取的确定范围内工作。我放在这里是因为我不知道问题是否出在这个函数上。
def getUrl(opt, baseUrl):
destino = "/home/ivanhercaz/monedasWiki/img"
print "Instrucciones del script \n No te preocupes, no es complicado pero atiende a los pasos"
print "Introduce 1 para obtener los archivos del 00001 al 00010"
print "Introduce 2 para obtener los archivos del 00010 al 00099"
print "Introduce 3 para obtener los archivos del 00100 al 00999"
print "Introduce 4 para obtener los archivos del 01000 al 09999"
print "Introduce 5 para obtener los archivos del 10000 al 19999"
optSel = int(input(opt))
# i es el rango
# urlI es la transformacion de i en cadena
# baseUrl es el enlace al sitio web de Pliego
# url es la url completa con los parametros necesarios
if optSel == 1:
try:
for i in range(0,10):
r = str(0).zfill(4)
urlI = str(i)
url = baseUrl + r + urlI
main(url, destino)
except ValueError:
print "Introduce el rango correcto"
elif optSel == 2:
try:
for i in range(10,100):
r = str(0).zfill(3)
urlI = str(i)
url = baseUrl + r + urlI
main(url, destino)
except ValueError:
print "Introduce el rango correcto"
elif optSel == 3:
try:
for i in range(100,1000):
r = str(0).zfill(2)
urlI = str(i)
url = baseUrl + r + urlI
main(url, destino)
except ValueError:
print "Introduce el rango correcto"
elif optSel == 4:
try:
for i in range(1000,10000):
r = str(0).zfill(1)
urlI = str(i)
url = baseUrl + r + urlI
main(url, destino)
except ValueError:
print "Introduce el rango correcto"
elif optSel == 2:
try:
for i in range(10000,18510):
urlI = str(i)
url = baseUrl + r + urlI
main(url, destino)
except ValueError:
print "Introduce el rango correcto"
elif optSel < 0:
print "Valor inferior a 0"
else:
print "Algo ha salido mal"
这两个函数都在同一个文件中。如果您能告诉我出了什么问题,我将不胜感激。
编辑: 我已经改变了打开和写入文件的方式,就像 Moses Koledoye 评论的那样,但是脚本只写入了最后检查的文本。我认为问题与检查和添加带有文本的行的循环有关,但我没有找到解决它的方法。我再次分享 main()。
<!-- language: python -->
def main(url, destino):
""" Acceso al sitio web """
soup = bs(urlopen(url), 'lxml')
parsed = list(urlparse.urlparse(url))
""" Acceso al archivo csv """
fileName = 'datos/datos.csv'
print fileName
""" Acceso a la descr. y escritura en el csv """
description = soup.findAll(True, {'class':['description']})
for text in description:
loteNum = text.contents[1]
loteDat = text.contents[3]
detalle = text.contents[6]
detalleE = detalle.encode("utf-8")
print loteNum
print loteDat
print detalle
header = ["Lote", "Dato del lote", "Detalles"]
data = [loteNum, loteDat, detalleE]
with open(fileName, 'w') as f:
f = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
f.writerow(header)
f.writerow(data)
""" Descarga de las img. """
for image in soup.findAll(True, {'class':['list_logo']}):
print "Image: %(src)s" % image
image_url = urlparse.urljoin(url, image['src'])
filename = image["src"].split("/")[-1]
outpath = os.path.join(destino, filename)
urlretrieve(image_url, outpath)
请您参考如下方法:
for text in description:
# ... some functionality
data = [loteNum, loteDat, detalleE]
with open(fileName, 'w') as f:
f = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
f.writerow(header)
f.writerow(data)
每次您遍历描述时,您现在都会以write 模式打开文件,这将覆盖以前的内容。 p>
您可以将它(打开文件的模式)更改为a追加,或者只是打开文件写入到循环外,比如这个:
with open(fileName, 'w') as f:
f = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
header = ["Lote", "Dato del lote", "Detalles"]
f.writerow(header)
for text in description:
loteNum, loteDat, detalle = [text.contents[i] for i in (1, 3, 6)]
detalleE = detalle.encode("utf-8")
print loteNum, loteDat, detalle
data = [loteNum, loteDat, detalleE]
f.writerow(data)
