2016-07-23 41 views
0

写在excel中递归数据我有一个叫做网页列表:html从Python列表

每个

一位html(i)元素提取我的电子邮件地址。我把这些电子邮件地址列表:email

我要生成一个Excel文件这样的:

enter image description here

为了写上一个Excel文件,所有我发现电子邮件地址。

由于每个html(i)页面可能包含不同数量的电子邮件地址,因此我想编写一个代码来自动考虑每页找到的不同电子邮件数量。

我的想法是与此类似:

#set the standard url to generate the full list of urls to be analyzed 
url = ["url1","url2", "url3", "url-n"] 

#get all the url pages' html codes 
for i in range (0,len(url): 
    html=[urllib.urlopen(url[i]).read() for i in range(0,len(url)) ] 

#find all the emails in each html page. 
for i in range (0,len(url): 
    emails = re.findall(r'[\w\.-][email protected][\w\.-]+', html[i]) 

#create an excel file 
wb = Workbook() 

#Set the excel file. 
for i in range (0,len(html)): 
    for j in range (0, len(emails)): 
     sheet1.write(i, j, emails[j]) 

wb.save('emails contact2.xls') 

当然是行不通的。它只写入list html最后一个元素中包含的电子邮件地址。有什么建议么?

+0

我不确定我明白你描述的'emails'列表是什么。它是某种嵌套列表吗?如果没有,你可能需要在你的外部循环中生成它(而不是提前)。 – Blckknght

+0

1个列表'emails'没有任何意义..你如何分开每个'html'的邮件?你有每个'html'的列表吗?也许你想使用'dict'? –

+0

我修改了代码,粘贴了我正在处理的内容。我希望你们更清楚。感谢您的帮助 –

回答

0
import xlwt 
wb = Workbook() 
sheet1 = wb.add_sheet("Sheet 1") 

htmls = generate_htmls() #Imaginary function to pretend it's initialized. 
for i in xrange(len(htmls)): 
    sheet1.write(i, 0, htmls[i]) 
    emails = extract_emails(htmls[i]) #Imaginary function to pretend it's extracted 
    for j in xrange(len(emails)): 
     sheet1.write(i, j + 1, emails[i]) 

假设您单独提取列表emails每个HTML,这些代码会将HTML中的第一个(索引0)列,然后把所有的电子邮件中index + 1(不覆盖第一列)。

+0

它的工作原理,感谢Yotam –

+0

@GiacomoBonvini谢谢你将我的答案标记为正确。但我有一个问题要问你 - 你明白为什么它有效吗?因为我不想让人们复制粘贴我的答案,我希望人们向他们学习。你有没有明白,还是应该补充一些解释? –

+0

感谢您的想法。我想我已经理解它是如何工作的。它逐行写入固定第一列中的html,然后将电子邮件写入其他列。正确?当然,如果你有任何其他意见,欢迎。我开始在python 3天前编程eheh –

0

我不知道xlwt,但考虑到你有每个htmlemails列表会这样的工作?

import xlwt 
wb = Workbook() 

for html_index, html in enumerate(html): 
    sheet1.write(html_index, 0, html.address) 
    for email_index, email in enumerate(emails_for_html): 
      sheet1.write(html_index, email_index + 1, email) 

wb.save('email contacts.xls') 

请注意,我不知道xlwt特定的命令,只是想模仿你的。

+0

'enumerate'基于0,所以在'email_index'中写入将覆盖第一列中的html ..它应该是'email_index + 1' :-) –

+0

@Yotam鲑鱼你是对的:)更新 –

+0

感谢您的编辑!另外,'enumerate(email_for_html,1)'(提供一个初始值为1)的选项也是可以的;-) –