2016-07-15 65 views
0

我是新来美丽的汤,我试图提取出现在页面上的信息。此信息包含在div class =“_ 50f3”中,根据用户可以包含多个信息(研究,学习,作品,工作,生活等)。所以,到目前为止,我已成功虽然下面的代码来解析DIV类,但我不知道如何提取我从想要的信息..提取页面介绍信息与美丽的汤

table = soup.findAll('div', {'class': '_50f3'}) 

[<div class="_50f3">Lives in <a class="profileLink" data-hovercard="/ajax/hovercard/page.php?id=114148045261892" href="/Fort-Worth-Texas/114148045261892?ref=br_rs">Fort Worth, Texas</a></div>, 
<div class="_50f3">From <a class="profileLink" data-hovercard="/ajax/hovercard/page.php?id=111762725508574" href="/Dallas-Texas/111762725508574?ref=br_rs">Dallas, Texas</a></div>] 

例如,在上面,我想存储“生活在”:“德克萨斯州的沃斯堡”和“来自”:“德克萨斯州达拉斯”。但在最一般的情况下,我想存储那里的任何信息。

任何帮助非常感谢!

回答

2

在一般的情况下,这只是你需要get_text() - 这将构建一个单一的元素文本字符串通过子节点递归去:

table = soup.find_all('div', {'class': '_50f3'}) 
print([item.get_text(strip=True) for item in table]) 

但是,你也可以单独提取的标签和值:

d = {} 
for item in table: 
    label = item.find(text=True) 
    value = label.next_sibling 

    d[label.strip()] = value.get_text() 

print(d) 

打印:

{'From': 'Dallas, Texas', 'Lives in': 'Fort Worth, Texas'} 
1
for i in range(len(table)): 
    print(table[i].text) 

应该工作