2017-10-15 123 views
1

嵌套元素我有下面的HTML:访问与beautifulsoup

<div id="contentDiv"> 
    <!-- START FILER DIV --> 
    <div style="margin: 15px 0 10px 0; padding: 3px; overflow: hidden; background-color: #BCD6F8;"> 
    <div class="mailer">Mailing Address 
     <span class="mailerAddress">500 ORACLE PARKWAY</span> 
     <span class="mailerAddress">MAIL STOP 5 OP 7</span> 
     <span class="mailerAddress">REDWOOD CITY CA 94065</span> 
    </div> 

我试图进入“500 ORACLE PARKWAY”和“邮站5 OP &”,但我不能找到一个方法来做到这一点。我的尝试是这样的:

for item in soup.findAll("span", {"class" : "mailerAddress"}): 
    if item.parent.name == 'div': 
     return_list.append(item.contents) 

编辑:我忘了提,有后的元素在HTML中使用类似的标签,以便它捕获所有的时候我只是想第2位。

编辑:链接:https://www.sec.gov/cgi-bin/browse-edgar?CIK=orcl

+0

,你遇到了什么样的错误?我试过你的代码,我可以看到你能够检索每个span元素中的文本。 – Ali

+0

你能发布HTML代码的链接吗? – Ali

+0

当您在该页面上提供了一个完美的XML文档时,为什么要尝试解释HTML:https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany & CIK = 0001341439 & CIK = 0001341439 &类型= & dateb = &所有者=包括&开始= 0 &计数= 40 &输出=原子。美丽的汤只应该是最后的可能选项。 –

回答

0

我要去尝试与所述信息的一点,我们必须回答这个问题。如果您只想要网页上某个类的前两个元素,则可以使用切片。

soup.findAll("span", {"class" : "mailerAddress"})[0:2] 
0

试试这个:

from bs4 import BeautifulSoup 
import requests 

res = requests.get("https://www.sec.gov/cgi-bin/browse-edgar?CIK=orcl").text 
soup = BeautifulSoup(res,'lxml') 
for item in soup.find_all(class_="mailerAddress")[:2]: 
    print(item.text) 

结果:

500 ORACLE PARKWAY 
MAIL STOP 5 OP 7