2016-07-06 8 views

Antwort

7

Sie einen CSS-Selektor, dies zu tun verwenden können:

In [57]: from bs4 import BeautifulSoup 

In [58]: soup = BeautifulSoup("""<div> 
    ....:  <p>this is some text</p> 
    ....:  <p>...and this is some other text</p> 
    ....: </div>""", "html.parser") 

In [59]: soup.select('div > p')[1].get_text(strip=True) 
Out[59]: '...and this is some other text' 
+0

Kann nicht pythonischer sein! – hashcode55

+3

@ hashcode55 Wie wäre es mit: 'supp.select_one ('div> p: n-type (2)'). Get_text (strip = True)'? – alecxe

+0

danke. das ist genau das, was ich gesucht habe – user3885884

1
secondp = [div.find('p') for div in soup.find('div')] 

In : secondp[1].text 

Out : Your text 

Oder Sie können die Verwendung findChildren direkt -

div_ = soup.find('div').findChildren() 
for i, child in enumerate(div_): 
    if i == 1: 
     print child.text 
5

Sie können n-of-Typ:

h = """<div> 
    <p>this is some text</p> 
    <p>...and this is some other text</p> 
</div>""" 


soup = BeautifulSoup(h) 

print(soup.select_one("div p:nth-of-type(2)").text) 
+0

Sie versprach, bei 100k zu stoppen! – alecxe

+0

@alecxe, ich habe versehentlich eine Registerkarte geöffnet und ich sah die beautifulsoup-Tag, das ist definitiv es, nur den Browser schließen jetzt schwöre ich;) –