(使用Python)将输出放入2个列表中,并将两个列表中的每个元素进行配对

问题描述:

我想制定一些脚本,使用Python和BeautifulSoup在网页上拾取一些文本,并将它们很好地放在一起。他们理想的结果是这样的:(使用Python)将输出放入2个列表中,并将两个列表中的每个元素进行配对

Port_new_cape Jan 23, 2009 12:05 
Brisbane July 24, 2002 03:12 
Liaoning Aug 26, 2006 02:55 

因为网页是在该公司的网站需要身份验证和重定向,我的目标页面的源代码复制到一个文件并将其保存为example.html在C:\为了方便。源代码的

部分是引述如下(它们在目标段落,并有更多的相似段落):

<tr class="ghj"> 
    <td><span class="city-sh"><sh src="./citys/1.jpg" alt="boy" title="boy" /></span><a  href="./membercity.php?mode=view&amp;u=12563">Port_new_cape</a></td> 
    <td class="position"><a href="./search.php?id=12563&amp;sr=positions" title="Search  positions">452</a></td> 
    <td class="details"><div>South</div></td> 
    <td>May 09, 1997</td> 
    <td>Jan 23, 2009 12:05 pm&nbsp;</td> 
</tr> 

<tr class="ghj"> 
    <td><span class="city-sh"><sh src="./citys/1.jpg" alt="boy" title="boy" /></span><a href="./membercity.php?mode=view&amp;u=12563">Brisbane</a></td> 
    <td class="position"><a href="./search.php?id=12563&amp;sr=positions" title="Search positions">356</a></td> 
    <td class="details"><div>South</div></td> 
    <td>Jun 09, 1986</td> 
    <td>July 24, 2002 03:12 pm&nbsp;</td> 
</tr> 

<tr class="ghj"> 
    <td><span class="city-sh"><sh src="./citys/1.jpg" alt="boy" title="boy" /></span><a href="./membercity.php?mode=view&amp;u=12563">Liaoning</a></td> 
    <td class="position"><a href="./search.php?id=12563&amp;sr=positions" title="Search positions">1105</a></td> 
    <td class="details"><div>Southeast</div></td> 
    <td>March 09, 2007</td> 
    <td>Aug 26, 2006 02:55 pm&nbsp;</td> 
</tr> 

到目前为止,以下是我有什么(在多亏了脚本的某些部分绅士的帮助):

from bs4 import BeautifulSoup 
import re 
import urllib2 

url = r"C:\example.html" 
page = open(url) 
soup = BeautifulSoup(page.read()) 


#preparing the 1st list 
cities = soup.find_all(href=re.compile("u=")) 

LST = [] 

for city in cities: 
    ci = city.renderContents() 
    full_list = LST.append(ci) 


#preparing the 2nd list 

Dates = soup.find_all('td', {'class' : 'info'}) 

LSTTT = [] 

counter = 0 

while len(Dates) > counter: 
    datesGroup = Dates[counter].find_next_siblings('td') 
    if len(datesGroup) == 2: 
     ti = datesGroup[1].renderContents() 
     full_list_2 = LSTTT.append(ti) 

    counter += 1 


print full_list 

print full_list_2 

我的想法是把所有的输出入2所列出,然后再结合各要素(他们要在2所列出通讯员一对一)。但是,当我运行脚本时,它会生成2个“无”列表。

我的问题:

  1. 出了什么问题的列表?为什么他们是“无”?
  2. 如何结合2个列表中的每个元素,一旦它们成功?

非常感谢。

list.append方法返回None,因为它是就地操作。而是将结果存储在其他变量,你可以使用LSTTLSTTT,因为他们,这样

ci = city.renderContents() 
LST.append(ci) 
... 
... 
    ti = datesGroup[1].renderContents() 
    LSTTT.append(ti) 
... 
... 
print(zip(LSTT, LSTTT)) 

zip函数返回所有的输入iterables的相应元素的元组的列表。

如果你要打印的压缩结果,withtout元组,你可以在它们之间迭代,这样

for item1, item2 in zip(LSTT, LSTTT): 
    print(item1, item2) 
+0

thefourtheye,这是不可思议的!谢谢。因为我需要单独存储结果。有没有一种方法不使用元组,而是成对打印而不是写:print LST [1] + LSTTT [0] ... print LST [-1] + LSTTT [-1]? –

+0

@MarkK你可以迭代数据,就像我在答案中显示的一样。请检查。 :) – thefourtheye

+0

再次感谢,thefourtheye。你是一位大师。 –