【问题标题】:how to fill excel file from selenium scraping in loop with python如何使用python循环从selenium抓取中填充excel文件
【发布时间】:2020-09-16 20:21:10
【问题描述】:

我正在尝试抓取一个网站而不是包含许多页面, 使用 selenium,我每次在第二个“TAB”中打开一个页面并启动我的函数来获取数据。 之后我关闭选项卡并打开下一个选项卡并继续提取直到最后一页。 我的问题是当我将数据保存在 excel 文件中时,我发现它只保存了从最后一页(选项卡)中提取的最后信息。 你能帮我找出我的错误吗?

def scrape_client_infos(linksss):

tds=[] # tds is the list that contain the data

reader=pd.read_excel(r'C:\python projects\mada\db.xlsx')
writer= pd.ExcelWriter(r'C:\python projects\mada\db.xlsx',engine='openpyxl')
html = urlopen(linksss)
soup=BeautifulSoup.BeautifulSoup(html,'html.parser')

table=soup.find('table',attrs={'class':'r2'})

#scrab all the tr that contain text    
for tr in table.find_all('tr'):
    elem = tr.find('td').get_text()
    elem=elem.replace('\t','')
    elem=elem.replace('\n','')
    elem=elem.replace('\r','')
    tds.append(elem)
    
print(tds)   

#selecting the data that i need to save in excel
raw_data={'sub_num':[tds[1]],'id':[tds[0]],'nationality':[tds[2]],'country':[tds[3]],'city':[tds[3]],'age':[tds[7]],'marital_status':[tds[6]],'wayy':[tds[5]]}    
df=pd.DataFrame(raw_data,columns=['sub_num','id','nationality','country','city','age','marital_status','wayy'])

#save the data in excel file
df.to_excel(writer, sheet_name='Sheet1',startrow=len(reader), header=False)
writer.save()
return soup        

P.S:我总是想从最后一行填写excel文件

【问题讨论】:

    标签: python excel selenium beautifulsoup openpyxl


    【解决方案1】:

    要使用 Pandas追加 excel 数据,您需要在 writer 对象中设置工作表。

    更新代码中的最后一部分:

    #save the data in excel file
    from openpyxl import load_workbook
    book = load_workbook(path)
    startrw = book['Sheet1'].max_row+1
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)  # prevent overwrite
    df.to_excel(writer, sheet_name='Sheet1',startrow=startrw, header=False)
    writer.save()
    return soup   
    

    【讨论】:

    • 还是一样的结果,只是保存在excel文件中的最后一条记录
    • 您可以在 selenium 中通过 reader java 读取、写入 excel 文件(您的项目中有 excel reader 的 utils 类)
    • startrow 可能存在问题。答案已更新。请重试。
    • 谢谢,效果很好。只有一件事,在每个插入行之后我得到的 excel 文件中都有一个空行(空白行),有什么办法可以避免它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多