Python 3 - 从 beautifulSoup 中的标签获取文本

Python 3 - Get text from tag in beautifulSoup

我正在使用 beautifulSoup 从网站提取数据。每次重新加载页面时,来自该网站的文本都会发生变化,所以基本上我希望能够将焦点设置为 class 名称作为静态变量,因为文本是动态的。

import requests
from bs4 import BeautifulSoup
url = 'xxxxxxxxxxx'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
class2 = soup.find_all(True, class_="template_title")
print (class2)

打印出
<td align="left" class="template_title" height="50" valign="bottom" width="535"><div style="padding-bottom:9px;">4</div></td>
当页面重新加载时,我仍然会关注该区域,但我不知道如何只打印文本(在本例中为:4)

弄清楚后,我还有一个问题:如果 class 包含多个标签,是否有办法获取更多静态数据以确保它只打印我正在搜索的文本而不是更多的? (我有 class,但我可以使用 height="50" valign="bottom" width="535" 吗?)

  1. 您可以使用元素的 textstring 属性。

    elems = soup.find_all(True, class_='template_title')
    print([elem.string for elem in elems])
    # prints `['4']` for the given html snippet
    
  2. 根据需要指定更多属性:

    elems = soup.find_all(True, class_='template_title',
                          height='50', valign='bottom', width='535')
    
  1. 我一般用.get_text()

  2. 是的,你可以

    有一个方法:.find_all(name, attrs, recursive, string, limit, **kwargs)

    **kwargs :接收任何像 height ,valign ,width

    attrs = {'height':'50','valign':'bottom'}