【问题标题】:BeautifulSoup, extracting strings within HTML tags, ResultSet objectsBeautifulSoup,提取 HTML 标签中的字符串,ResultSet 对象
【发布时间】:2016-02-04 07:11:41
【问题描述】:

我很困惑如何将 ResultSet 对象与 BeautifulSoup 一起使用,即bs4.element.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'

【问题讨论】:

    标签: html beautifulsoup python-requests


    【解决方案1】:

    class_='sister' 进行find_all() 过滤。

    注意:注意class 后面的下划线。这是一个特殊情况,因为 class 是保留字。

    搜索具有特定 CSS 类的标签非常有用,但是 CSS 属性的名称“class”是 Python 中的保留字。 使用 class 作为关键字参数会给你一个语法错误。作为 Beautiful Soup 4.1.2,您可以使用关键字按CSS类搜索 论据class_

    来源: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class

    一旦你拥有了所有带有 class Sister 的标签,请在它们上调用 .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
    

    【讨论】:

    • 效果很好,谢谢。我很困惑,因为“sistertags.text”抛出了一个错误
    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2021-12-05
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多