2016-04-22 18 views
0

Wo ist der Fehler? Ich möchte meinen Text ohne Tags analysieren.AttributeError: 'ResultSet' Objekt hat kein Attribut 'find_all'

from bs4 import BeautifulSoup  
import re 
import urllib.request 
f = urllib.request.urlopen("http://www.championat.com/football/news-2442480-orlov-zenit-obespokoen---pole-na-novom-stadione-mozhet-byt-nekachestvennym.html") 

soup = BeautifulSoup(f, 'html.parser') 

soup=soup.find_all('div', class_="text-decor article__contain") 

invalid_tags = ['b', 'i', 'u', 'br', 'a'] 

for tag in invalid_tags: 

    for match in soup.find_all(tag): 

     match.replaceWithChildren() 

soup = ''.join(map(str, soup.contents)) 

print (soup) 

Fehler:

Traceback (most recent call last): 
    File "1.py", line 9, in <module> 
    for match in soup.find_all(tag): 
AttributeError: 'ResultSet' object has no attribute 'find_all' 
+0

Sie ersetzt ' Suppe "mit einem Resultset:' suppe = supp.find_all ('div', Klasse _ = "text-decor article__contain") '. Ein Resulset ist einfach eine Liste mit einem zusätzlichen Verweis auf das ursprüngliche Suppenobjekt. Es ist mir nicht klar, warum Sie das 'BeautifulSoup'-Objekt durch ein Resultset ersetzen. Wenn Sie eine geschachtelte Suche durchführen möchten, verwenden Sie einen [CSS-Selektor] (https://www.crummy.com/software/BeautifulSoup/bs4/). doc/# css-selectors). –

+0

Sie möchten auch [Ausgabeformatierung] (https://www.crummy.com/software/BeautifulSoup/bs4/doc/#output) betrachten, die Objekte nicht auf Zeichenketten abbilden. –

Antwort

0

soup=soup.find_all('div', class_="text-decor article__contain")

Auf dieser Linie soup wird eine ResultSet Instanz - im Grunde eine Liste der Tag Instanzen. Und Sie bekommen die 'ResultSet' object has no attribute 'find_all', da diese ResultSet Instanz keine find_all() Methode hat. FYI, wird dieses Problem tatsächlich in der troubleshooting section in der Dokumentation beschrieben:

AttributeError: 'ResultSet' object has no attribute 'foo' - This usually happens because you expected find_all() to return a single tag or string. But find_all() returns a list of tags and strings–a ResultSet object. You need to iterate over the list and look at the .foo of each one. Or, if you really only want one result, you need to use find() instead of find_all() .

Und Sie wirklich ein Ergebnis wollen, da es einen einzigen Artikel auf der Seite lautet:

soup = soup.find('div', class_="text-decor article__contain") 

Beachten Sie aber, dass es keine Notwendigkeit Tags eines nach dem anderen zu finden, können Sie eine Liste von Variablennamen übergeben direkt an find_all()-BeautifulSoup bei der Suche nach Elementen ziemlich flexibel ist:

article = soup.find('div', class_="text-decor article__contain") 

invalid_tags = ['b', 'i', 'u', 'br', 'a'] 
for match in article.find_all(invalid_tags): 
    match.unwrap() # bs4 alternative for replaceWithChildren 
Verwandte Themen