【问题标题】:[Py3,BS]How can I get the value of a div element [duplicate][Py3,BS]How can I get the value of a div element [duplicate]
【发布时间】:2021-07-18 00:30:17
【问题描述】:

你好! 我想使用 Python 和 BeautifulSoup 将 div 内的文本“接受”作为字符串。

<div class="wordlist-item">accepted</div>

使用下面的代码,输出不是我想要的。

table = soup2.findAll("div", attrs={"class": "wordlist-item"})

输出:

<div class="wordlist-item">accepted</div>

谢谢!

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    使用.text.get_text()

    html_doc = """
        <div class="wordlist-item">accepted</div>
    """
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    print(soup.find("div", class_="wordlist-item").text)
    

    打印:

    accepted
    

    注意:当你使用.findAll()时,你必须迭代结果:

    table = soup.findAll("div", attrs={"class": "wordlist-item"})
    for div in table:
        print(div.text)
    

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-11-20
      • 2022-12-26
      • 2022-12-02
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      • 2022-12-02
      • 2022-12-27
      相关资源
      最近更新 更多