2017-07-22 1 views
1

Ich habe den folgenden Code in main.pyWie wird die ursprüngliche Zeichenfolge von bs4.element.Tag mit dem äußersten Tag entfernt?

#!/usr/bin/env python 
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1: 

import sys 
from bs4 import BeautifulSoup 

soup = BeautifulSoup(sys.stdin.read(), 'html.parser') 
print type(soup.find('a')) 
print str(soup.find('a')) 

Das Ergebnis ist die folgende. Aber ich möchte nicht, dass das äußerste Etikett (d. H. Und in diesem Fall) gedruckt wird. Gibt es eine Möglichkeit, die ursprüngliche Zeichenfolge ohne das äußerste Tag robust zu drucken?

$ ./main.py <<EOF 
> <a>x<b>y</b></a> 
> EOF 
None 
<class 'bs4.element.Tag'> 
<a>x<b>y</b></a> 
+0

'soup.find ('a'). Text' oder' soup.find ('a'). Strings' oder 'soup.find ('a ') .contents' –

+0

@tmadam warum nicht dies als Antwort posten? Es ist der Richtige! =) –

Antwort

0
print soup.find('a').get_text() 

oder

tag_string = '' 
for item in soup.find('a').contents: 
    tag_string += str(item) 
print tag_string 
Verwandte Themen