2015-11-03 2 views
3

Я смущен точно, как я могу использовать объект ResultSet с помощью BeautifulSoup, то есть bs4.element.ResultSet.BeautifulSoup, извлечение строк в тегах HTML, объекты ResultSet

После использования find_all(), как можно извлечь текст?

Пример:

В документации bs4, HTML-документ html_doc выглядит следующим образом:

<p class="story"> 
    Once upon a time there were three little sisters; and their names were 
    <a class="sister" href="http://example.com/elsie" id="link1"> 
    Elsie 
    </a> 
    , 
    <a class="sister" href="http://example.com/lacie" id="link2"> 
    Lacie 
    </a> 
    and 
    <a class="sister" href="http://example.com/tillie" id="link2"> 
    Tillie 
    </a> 
    ; and they lived at the bottom of a well. 
    </p> 

Один начинается с создания soup и найти все href,

from bs4 import BeautifulSoup 
soup = BeautifulSoup(html_doc, 'html.parser') 
soup.find_all('a') 

, который выводит

[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
    <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 
    <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] 

Мы могли бы также сделать

for link in soup.find_all('a'): 
    print(link.get('href')) 

, который выводит

http://example.com/elsie 
http://example.com/lacie 
http://example.com/tillie 

Я хотел бы получить только текст из class_="sister", т.е.

Elsie 
Lacie 
Tillie 

Можно попробовать

for link in soup.find_all('a'): 
    print(link.get_text()) 

, но это приводит к ошибке:

AttributeError: 'ResultSet' object has no attribute 'get_text' 

ответ

4

Выполните find_all() фильтрацию class_='sister'.

Примечание: Обратите внимание на подчеркивают после class. Это особый случай, потому что класс является зарезервированным словом.

It’s very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, “class”, is a reserved word in Python. Using class as a keyword argument will give you a syntax error. As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_ :

Источник:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class

После того как вы все теги с классом сестры, вызовите .text на них, чтобы получить текст. Обязательно удалите текст.

Например:

from bs4 import BeautifulSoup 

html_doc = '''<p class="story"> 
    Once upon a time there were three little sisters; and their names were 
    <a class="sister" href="http://example.com/elsie" id="link1"> 
    Elsie 
    </a> 
    , 
    <a class="sister" href="http://example.com/lacie" id="link2"> 
    Lacie 
    </a> 
    and 
    <a class="sister" href="http://example.com/tillie" id="link2"> 
    Tillie 
    </a> 
    ; and they lived at the bottom of a well. 
    </p>''' 

soup = BeautifulSoup(html_doc, 'html.parser') 
sistertags = soup.find_all(class_='sister') 
for tag in sistertags: 
    print tag.text.strip() 

Выход:

(bs4)macbook:bs4 joeyoung$ python bs4demo.py 
Elsie 
Lacie 
Tillie 
+0

Это прекрасно работает, спасибо. Я был смущен, потому что «sistertags.text» выдавал ошибку – ShanZhengYang

Смежные вопросы