【发布时间】:2015-11-17 02:59:47
【问题描述】:
我正在尝试从多个 html 页面收集数据,特别是列表元素中的数据。我试图将此数据添加到字典中以供以后使用,我必须按预期提取数据,但我将数据输入到字典中没有按预期工作。我目前正在覆盖每个条目,而不是添加新条目。谁能指出我哪里出错了?
当前代码
from BeautifulSoup import BeautifulSoup
import requests
import re
person_dict = {}
.....
<snip>
<snip>
.....
soup = BeautifulSoup(response.text)
div = soup.find('div', {'id': 'object-a'})
ul = div.find('ul', {'id': 'object-a-1'})
li_a = ul.findAll('a', {'class': 'title'})
li_p = ul.findAll('p', {'class': 'url word'})
li_po = ul.findAll('p')
for a in li_a:
nametemp = a.text
name = (nametemp.split(' - ')[0])
person_dict.update({'Name': name}) #I attempted updating
for lip in li_p:
person_dict['url'] = lip.text #I attempted adding directly
for email in li_po:
reg_emails = re.compile('[a-zA-Z0-9.]*' + '@')
person_dict['email'] = reg_emails.findall(email.text)
print person_dict # results in 1 entry being returned
测试数据
<div id="object-a">
<ul id="object-a-1">
<li>
<a href="www.url.com/person" class="title">Person1</a>
<p class="url word">www.url.com/Person1</p>
<p>Person 1, some foobar possibly an email@address.com ...</p>
</li>
<li>
<a href="www.url.com/person" class="title">Person2</a>
<p class="url word">www.url.com/Person1</p>
<p>Person 2, some foobar possibly an email@address.com ...</p>
</li>
<li>
<a href="www.url.com/person" class="title">Person3</a>
<p class="url word">www.url.com/Person1</p>
<p>Person 3, some foobar, possibly an email@address.com ...</p>
</li>
</ul>
【问题讨论】:
-
每次迭代都使用
'Name'键,不是吗?键必须是唯一的。 -
是的,我想在每次迭代中添加一个新的
Name和相关数据 -
为什么需要字典,只需将元组附加到列表中,例如
List.append((name, email, foo)) -
我的印象是字典形式会更方便。但我当然对编码很陌生,你能解释一下为什么最好有一个元组列表吗?
标签: python html beautifulsoup