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

2024-04-25 11:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一些脚本,使用Python和BeautifulSoup在网页上提取一些文本,并将它们很好地组合在一起。理想结果如下:

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

由于该网页位于需要身份验证和重定向的公司网站中,为了方便起见,我将目标网页的源代码复制到一个文件中,并将其保存为C:example.html。你知道吗

下面引用部分源代码(它们是目标段落,还有更多类似段落):

<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. 一旦成功,如何将两个列表中的每个元素组合起来?你知道吗

非常感谢。你知道吗


Tags: divcitytitleshtrfulllistclass
1条回答
网友
1楼 · 发布于 2024-04-25 11:38:53

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

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

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

如果你想打印压缩后的结果,不需要元组,你可以像这样迭代它们

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

相关问题 更多 >