【问题标题】:Python Beautiful Soup: get text from elementPython Beautiful Soup:从元素中获取文本
【发布时间】:2026-02-12 02:35:02
【问题描述】:

我正在循环遍历 <td> 类型的元素,但我正在努力提取 <td> 文本。

HTML:

<td class="cell">
 Brand Name 1
 <br/>
 (
 <a class="tip" title="This title">
  Authorised Resellers
 </a>
 )
</td>

:期望的输出:

Brand name: Brand name 1
Brand distribution type: Authorised Reseller

我试过了:

for brand in brand_loop:
  print(brand.text)

但这不会打印开始 &lt;td&gt; 标记(“品牌名称 1”)之后的文本。

有什么建议吗?谢谢!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    试试

    for brand in brand_loop:
      print(brand.text)
      print(brand.find('a').text)
    

    您只能直接打印所选元素的文本。

    【讨论】:

      【解决方案2】:

      您可以选择&lt;td class="cell"&gt;,然后选择.find_next(text=True)获取品牌名称,然后选择.find_next('a')获取品牌分布类型。

      例如:

      txt = '''<td class="cell">
       Brand Name 1
       <br/>
       (
       <a class="tip" title="This title">
        Authorised Resellers
       </a>
       )
      </td>'''
      
      
      soup = BeautifulSoup(txt, 'html.parser')
      
      brand_name = soup.select_one('td.cell').find_next(text=True)
      bran_distribution = brand_name.find_next('a').text
      
      print('Brand name:', brand_name.strip())
      print('Brand distribution type:', bran_distribution.strip())
      

      打印:

      Brand name: Brand Name 1
      Brand distribution type: Authorised Resellers
      

      【讨论】:

        【解决方案3】:

        您可以使用find()next_element 获取第一个td 标记文本。而要获取a 标记文本,只需使用find()。你可以试试:

        from bs4 import BeautifulSoup
        html_doc = '''<td class="cell">
         Brand Name 1
         <br/>
         (
         <a class="tip" title="This title">
          Authorised Resellers
         </a>
         )
        </td>'''
        
        soup = BeautifulSoup(html_doc,'lxml')
        brand_name = soup.find("td").next_element.strip()
        brand_distribution_type = soup.find("a").text.strip()
        print('Brand name:', brand_name)
        print('Brand distribution type:', brand_distribution_type)
        

        输出将是:

        Brand name: Brand Name 1
        Brand distribution type: Authorised Resellers
        

        【讨论】: