Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法将完整的web获取值保存到csv文档中_Python_Python 3.x_Web Scraping_Beautifulsoup - Fatal编程技术网

Python 无法将完整的web获取值保存到csv文档中

Python 无法将完整的web获取值保存到csv文档中,python,python-3.x,web-scraping,beautifulsoup,Python,Python 3.x,Web Scraping,Beautifulsoup,我尝试从页面列表中获取值,并尝试将文件保存到csv文档中,但是csv文档仅将最后一个值存储在csv文档中 尝试了多种方法,但结果总是一样的 还有空白值的列需要填充NIL值,但是只张贴[]符号。 python新手,发现很难将其保存到python。需要您的支持才能完成此任务 我应如何进一步进行 import requests from bs4 import BeautifulSoup import csv import time def fin_car(url): x = {}

我尝试从页面列表中获取值,并尝试将文件保存到csv文档中,但是csv文档仅将最后一个值存储在csv文档中

尝试了多种方法,但结果总是一样的

还有空白值的列需要填充NIL值,但是只张贴[]符号。

python新手,发现很难将其保存到python。需要您的支持才能完成此任务

我应如何进一步进行

import requests
from bs4 import BeautifulSoup
import csv
import time
def fin_car(url):
    x = {}                                                                                                        
    y = []
    page = ''
    while page == '':
        try:
            page = requests.get(url)
        except:
            print("Connection refused by the server..")
            print("Let me sleep for 5 seconds")
            print("ZZzzzz...")
            time.sleep(5)
            print("Was a nice sleep, now let me continue...")
            continue
    #page = requests.get(url)                                                                                      
    soup = BeautifulSoup(page.content, 'lxml')                                                                    
    Precio = []                                                                                                   
    price = soup.find('div' , 'price').text                                                                                                                                            
    Precio = (str(price).strip())
    print (Precio)     
    #-------------------------------------------------------------------------------------------------------------#
    #                           #Tipo Propiedad          #Tipo de oferta                                          #
    #-------------------------------------------------------------------------------------------------------------#
    Tipo_Propiedad = []                                                                                           
    Tipo_de_oferta = []                                                                                           
    T_1 = soup.find('div' , 'box').h1.text
    text =  (str(T_1).strip())
    l = text.find(' ')
    m = text.find(' ', l+1)
    n = text.find(' ', m+1)
    Tipo_Propiedad = text[0 : l]
    Tipo_de_oferta = text[m+1 : n]
    print (Tipo_Propiedad)
    print (Tipo_de_oferta)
    #-------------------------------------------------------------------------------------------------------------#
    #                           #Departamento  #Ciudad #Zona #Barrio                                              #
    #-------------------------------------------------------------------------------------------------------------#
    Departamento = []                                                                                             
    Ciudad = []                                                                                                   
    Zona = []                                                                                                     
    Barrio = []                                                                                                   
    first = soup.find('div' , 'breadcrumb left')                                                                  
    link = first.find('div')                                                                                      
    a_link = link.findAll('a')                                                                                    
    box1 = []                                                                                                     
    for row in a_link:                                                                                            
        box1.append(row.text)                                                                                     
    Departamento = (box1[1:2].pop())                                                                          
    Ciudad = (box1[2:3].pop())                                                                                
    Zona = (box1[3:4].pop())                                                                                  
    Barrio = (box1[4:5])                                                                                
    print (Departamento)                                                                                     
    print (Ciudad)                                                                                           
    print (Zona)                                                                                             
    print (Barrio)
    #-------------------------------------------------------------------------------------------------------------#
    #              #Área     #Habitaciones  #Baños #Parqueaderos                                                  #
    #-------------------------------------------------------------------------------------------------------------#
    box_2 = soup.find('div' ,'features clearfix')                                                                 
    box_2_1  = box_2.findAll('span')                                                                              
    box2 = []                                                                                                     
    Área=[]                                                                                                       
    Habitaciones = []                                                                                             
    Baños = []                                                                                                    
    Parqueaderos = []                                                                                             
    for row2 in box_2_1:
        box2.append(str(row2.text).strip())
    for i in box_2_1:
        a = box2[0:1].pop()
        b = box2[1:2].pop()
        c = box2[2:3].pop()
        d = box2[3:4].pop()
        a1 = a[0 : a.find(' ')]
    Área = (a1)                                                                              
    Habitaciones = (b.rstrip()[-1])                                                                      
    Baños = (c.rstrip()[-1])                                                                             
    Parqueaderos =(d) 
    print (Área)                                                                                            
    print (Habitaciones)                                                                                    
    print (Baños)                                                                                           
    print (Parqueaderos)
    #-------------------------------------------------------------------------------------------------------------#
    #            #Área_Privada #Área_Const #Antigüedad #Admón #Estrato #Estado #Piso_No                           #
    #-------------------------------------------------------------------------------------------------------------#
     box_3 = soup.find('div' ,'row features_2 ')                                                                   
    box_3_1  = box_3.findAll('li')                                                                                                                                                                                   #
    Área_Privada = []                                                                                             
    Área_Const = []                                                                                               
    Antigüedad = []                                                                                               
    Admón = []                                                                                                    
    Estrato = []                                                                                                  
    Estado = []                                                                                                   
    Piso_No = []                                                                                                  
    for li in box_3_1:                                                                                            
        heading_words = li.b.text.split()                                                                                                                                                             #
        target_content = str(li.br.next_sibling).strip()                                                                                                                                             #
        if "privada:" in heading_words:                                                                           
            Área_Privada = (target_content)                                                                                                                                            #
        elif "Const.:" in heading_words:                                                                          
            Área_Const = (target_content)                                                                     
        elif "Antigüedad:" in heading_words:                                                                      
            Antigüedad = (target_content)                                                                     
        elif "Admón:" in heading_words:                                                                         
            Admón = (target_content)
        elif "Estrato:" in heading_words:                                                                         
            Estrato = (target_content)                                                                                                                                               
        elif "Estado:" in heading_words:                                                                          
            Estado = (target_content)                                                                         
        elif "Piso" in heading_words:                                                                             
            Piso_No = (target_content)                                                                           
    print (Área_Privada)                                                                                                                                                                                #
    print (Área_Const)                                                                                       
    print (Antigüedad)                                                                                       
    print (Admón)                                                                                            
    print (Estrato)                                                                                                                                                                                      #
    print (Estado)                                                                                           
    print (Piso_No[0:1])
    #-------------------------------------------------------------------------------------------------------------#
    #               #Actualizado             #Visitas               #Código_FincaRaiz                             #                                                                                        #
    #-------------------------------------------------------------------------------------------------------------#
    box4 = soup.find('div' , 'box_content row')                                                                   
    box4_1 = box4.findAll('span')                                                                                 
    vis = []                                                                                                      
    Actualizado = []                                                                                                         
    Visitas = []                                                                                                         
    Código_FincaRaiz = []                                                                                         
    for i in box4_1:                                                                                              
        vis.append((str(i.text).strip()))   
    for j in box4_1:
        e = vis[0:1].pop()
        f = vis[2:3].pop()
    Actualizado = e
    Código_FincaRaiz = f                                                                                   
    url="https://www.fincaraiz.com.co/WebServices/Statistics.asmx/GetAdvertVisits?idAdvert={}&idASource=40&idType=1001".format(Código_FincaRaiz)                                                                        #
    page1 = requests.get(url)                                                                                     
    soup1 = BeautifulSoup(page1.content , 'lxml')                                                                 
    visit1 = soup1.find('double').text                                                                            
    Visitas = (visit1)                                                                                                                                                                          
    print (Actualizado)                                                                                      
    print (Visitas)                                                                                          
    print (Código_FincaRaiz)
    #-------------------------------------------------------------------------------------------------------------#
    x['Código FincaRaiz'] = Código_FincaRaiz
    x['Departamento'] = Departamento
    x['Ciudad'] = Ciudad
    x['Zona'] = Zona
    x['Barrio'] = Barrio
    x['Tipo Propiedad'] = Tipo_Propiedad
    x['Tipo de oferta'] = Tipo_de_oferta
    x['Precio'] = Precio
    x['Área'] = Área
    x['Área Privada'] = Área_Privada
    x['Área Const.'] = Área_Const
    x['Antigüedad'] = Antigüedad
    x['Baños'] = Baños
    x['Habitaciones'] = Habitaciones
    x['Parqueaderos'] = Parqueaderos
    x['Admón'] = Admón
    x['Estrato'] = Estrato
    x['Estado'] = Estado
    x['Piso No.'] = Piso_No
    x['Actualizado'] = Actualizado
    x['Visitas'] = Visitas
    y.append(x)
x = {}                                                                                                        
y = []
filename = 'Fincar.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['Código FincaRaiz','Departamento','Ciudad','Zona','Barrio', 'Tipo Propiedad', 'Tipo de oferta',
                                  'Precio' , 'Área' , 'Área Privada' , 'Área Const.', 'Antigüedad', 'Baños' , 'Habitaciones',
                                  'Parqueaderos' , 'Admón', 'Estrato' , 'Estado' , 'Piso No.' , 'Actualizado', 'Visitas'])
    w.writeheader()
    for x in y:
        w.writerow(x)a
tab = []
xen = []
key_value = 'https://www.fincaraiz.com.co'
for i in range(2,6):
    tab.append('https://www.fincaraiz.com.co/finca-raiz/?ad=30|{}||||1||||||||||||||||||||||1|||1||||||'.format(i))
for j in tab:
    page = requests.get(j)
    soup = BeautifulSoup(page.content , 'lxml')
    index = soup.findAll('div' , 'span-title')
    for i in index:
        xen.append(i.find('a').get('href'))
    for j in xen:
        url = (key_value + j)
        fin_car(url)
这些值在不同的范围内。将
x
分配到车内
fin\u车
不会影响车外。您可以使用
global
语句来更改它,但更好的方法是从函数返回

即使您正在更改
x
y
的外部值,您也只能在写入CSV很久之后调用
fin\u car
。代码中事件的顺序很重要

我建议:

def fin_car(url):
    x = {}                                                                                                        
    y = []
...
x = {}                                                                                                        
y = []

您根本不需要
y

还有什么选项可以直接保存输出sql@sudharsonns是的,有很多选择,谷歌的“python sql”。如果您在某个特定问题上遇到困难,可以问一个新问题。什么是“创建一个bot来构建数据库”?尝试使用sqlite3将我的列表保存到database@sudharsonns机器人只是一个程序。我需要上下文来解释更多。但我认为这句话对于理解如何解决你的问题并不重要。
def fin_car(url):
    x = {}
    ...
    return x

with open...:
    w = csv.DictWriter(...)
    ...
    for j in tab:
        ...
        for j in xen:
            url = ...
            w.writerow(fin_car(url))