Python 从网站中抓取数据并写入csv文件时,只有最后一行写入该文件

Python 从网站中抓取数据并写入csv文件时,只有最后一行写入该文件,python,beautifulsoup,export-to-csv,Python,Beautifulsoup,Export To Csv,我正在使用python和BeautifulSoup从网页中提取数据,而且效果很好。问题是它没有将所有值插入csv文件。比如,如果我提取了10个数据值,而只有第10个数据值进入csv文件,那么第9个数据值不会。所有10个数据值都显示在终端上,但不在csv文件中 导入库 导入csv 导入urllib.request 从bs4导入BeautifulSoup #指定url 引用第页=”https://www.cardekho.com/Hyundai/Gurgaon/cardealers" #quote_

我正在使用python和BeautifulSoup从网页中提取数据,而且效果很好。问题是它没有将所有值插入csv文件。比如,如果我提取了10个数据值,而只有第10个数据值进入csv文件,那么第9个数据值不会。所有10个数据值都显示在终端上,但不在csv文件中

导入库
导入csv
导入urllib.request
从bs4导入BeautifulSoup
#指定url
引用第页=”https://www.cardekho.com/Hyundai/Gurgaon/cardealers"
#quote_page=input(“在此处输入数据源:”)
page=urllib.request.urlopen(引用页面)
#使用Beauty soup解析html并存储在变量'soup'中`
汤=美汤(第页,“lxml”)
#取出of name并获取其值
delrname=soup.find_all('div',class='deleadres')
对于delrname中的名称:
dname=name.find('div',class=“delrname”).text#name
打印(dname)
有关delrname中的地址:
dadres=地址。查找('p')。文本
打印(dadres)
对于delrname中的mobile:
dmobile=mobile.find('div',class=“clearfix”).text
打印(dmobile)
对于delrname中的电子邮件:
demail=email.find('div',class=“mobno”).text
打印(消磁)
#正在将数据导出到csv文件。。。。
将open('result.csv',换行符='')作为f:
r=csv.reader(f)
数据=[r中每行对应一行]
将open('result.csv','w',换行符='')作为f:
w=csv.writer(f)
w、 writerow(['NAME'、'ADDRES'、'MOBILE'、'EMAIL']))
w、 writerow([dname、dadres、dmobile、demail])**强文本**

在for循环中指定值时,替换前一个值。因此,在循环之外,您将得到最终值

for number in 1, 2, 3:
    print(number) # prints 1, then 2, then 3
print(number) # prints only 3, since that was the final value.
在脚本中,使用单个for循环提取值并将数据行写入csv

with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL']) # write header once
    entries = soup.find_all('div', class_='deleadres')
    for entry in entries: # loop over all `.deleadres` elements
        dname = entry.find('div', class_="delrname").text
        dadres = entry.find('p').text
        dmobile = entry.find('div', class_="clearfix").text
        demail = entry.find('div', class_="mobno").text
        w.writerow([dname,dadres,dmobile,demail]) # write data rows for each entry

您的错误是,您只保存循环中的最后一个值,因此没有获得所有值

另一种方法是:

1) 将循环中的值添加到列表中

2) 将列表中的值添加到CSV

page = urllib.request.urlopen(quote_page)
# CREATE NEW LISTS
dname_list = list()
dadres_list = list()
dmobile_list = list()
demail_list = list()


# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "lxml")

# APPEND TO THE LIST
# Take out the <div> of name and get its value
delrname = soup.find_all('div', class_='deleadres')
for name in delrname:
    dname = name.find('div', class_="delrname").text # name
    print(dname)
    dname_list.append(dname)
for address in delrname:
    dadres = address.find('p').text
    print(dadres)
    dadres_list.append(dadres)
for mobile in delrname:
    dmobile = mobile.find('div', class_="clearfix").text
    print(dmobile)
    dmobile_list.append(dmobile)
for email in delrname:
    demail = email.find('div', class_="mobno").text
    print(demail)
    demail_list.append(demail)


#exorting data into csv file....
with open('result.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL'])
    # TRAVERSE THROUGH THE LIST
    for i in range(len(dname)):
        try:
            w.writerow([dname_list[i],dadres_list[i],dmobile_list[i],demail_list[i]])
        except IndexError:
            print('')
page=urllib.request.urlopen(引用页面)
#创建新列表
dname_list=list()
数据列表=列表()
dmobile_list=list()
demail_list=list()
#使用Beauty soup解析html并存储在变量'soup'中`
汤=美汤(第页,“lxml”)
#追加到列表中
#取出of name并获取其值
delrname=soup.find_all('div',class='deleadres')
对于delrname中的名称:
dname=name.find('div',class=“delrname”).text#name
打印(dname)
dname_list.append(dname)
有关delrname中的地址:
dadres=地址。查找('p')。文本
打印(dadres)
dadres\u list.append(dadres)
对于delrname中的mobile:
dmobile=mobile.find('div',class=“clearfix”).text
打印(dmobile)
dmobile\u list.append(dmobile)
对于delrname中的电子邮件:
demail=email.find('div',class=“mobno”).text
打印(消磁)
demail_list.append(demail)
#正在将数据导出到csv文件。。。。
将open('result.csv',换行符='')作为f:
r=csv.reader(f)
数据=[r中每行对应一行]
将open('result.csv','w',换行符='')作为f:
w=csv.writer(f)
w、 writerow(['NAME'、'ADDRES'、'MOBILE'、'EMAIL']))
#遍历列表
对于范围内的i(len(dname)):
尝试:
w、 writerow([dname_列表[i]、dadres_列表[i]、dmobile_列表[i]、demail_列表[i])
除索引器外:
打印(“”)

附言:哈肯的答案是一个更好的方法。我只是想让你知道另一种方法

谢谢你指导我的问题。这非常有帮助,最终解决了我的问题。谢谢你指导我的问题。这非常有帮助,最终解决了我的问题不客气。在堆栈溢出时,您不需要写评论来表示感谢。相反,投赞成票(或反对票),接受最有用的答案。使用评论要求澄清或添加细节。我会记在心里的。事实上我是这里的初学者。
page = urllib.request.urlopen(quote_page)
# CREATE NEW LISTS
dname_list = list()
dadres_list = list()
dmobile_list = list()
demail_list = list()


# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "lxml")

# APPEND TO THE LIST
# Take out the <div> of name and get its value
delrname = soup.find_all('div', class_='deleadres')
for name in delrname:
    dname = name.find('div', class_="delrname").text # name
    print(dname)
    dname_list.append(dname)
for address in delrname:
    dadres = address.find('p').text
    print(dadres)
    dadres_list.append(dadres)
for mobile in delrname:
    dmobile = mobile.find('div', class_="clearfix").text
    print(dmobile)
    dmobile_list.append(dmobile)
for email in delrname:
    demail = email.find('div', class_="mobno").text
    print(demail)
    demail_list.append(demail)


#exorting data into csv file....
with open('result.csv',newline='') as f:
    r = csv.reader(f)
    data = [line for line in r]
with open('result.csv','w',newline='') as f:
    w = csv.writer(f)
    w.writerow(['NAME','ADDRES','MOBILE','EMAIL'])
    # TRAVERSE THROUGH THE LIST
    for i in range(len(dname)):
        try:
            w.writerow([dname_list[i],dadres_list[i],dmobile_list[i],demail_list[i]])
        except IndexError:
            print('')