【问题标题】:BeautifulSoup - how to extract text without opening tag and before <br> tag?BeautifulSoup - 如何在没有打开标签和 <br> 标签之前提取文本?
【发布时间】:2015-09-22 01:36:38
【问题描述】:

我是 python 和 beautifulsoup 的新手,花了好几个小时试图弄清楚这一点。
我想在没有类的&lt;div&gt; 中提取三个特定的文本提取。
我想要的第一个文本提取在 &lt;a&gt; 标签内,该标签在 &lt;h4&gt; 标签内。我设法将其提取出来。
第二个文本提取紧跟在结束 h4 标记 &lt;/h4&gt; 之后,然后是 &lt;br&gt; 标记。
第三个文本提取紧跟在第二个文本提取之后的&lt;br&gt; 标记之后,并且紧随其后的是&lt;br&gt; 标记。

这里是我使用的 html 提取:

<div>
    <h4 class="actorboxLink">
    <a href="/a-decheterie-de-bagnols-2689">Decheterie de Bagnols</a>
    </h4>
    Route des 4 Vents<br>
    63810 Bagnols<br>
</div>

我要提取:

Decheterie de Bagnols

Route des 4 Vents

63810 Bagnols

这是我目前的代码:

import urllib
from bs4 import BeautifulSoup    
data = urllib.urlopen(url).read()
soup = BeautifulSoup(data, "html.parser")
name = soup.findAll("h4", class_="actorboxLink")

for a_tag in name:
    print a_tag.text.strip()

我需要类似“soup.findAll(&lt;/h4&gt;) 之后的所有文本”

我使用 .next_sibling 玩过,但我无法让它工作。

有什么想法吗?谢谢

更新:
我试过这个:

for a_tag in classActorboxLink:
    print a_tag.find_all_next(string=True, limit=5) 

这给了我:
[u'\n', u'\r\n\t\t\t\t\t\tDecheterie\xa0de\xa0Bagnols\t\t\t\t\t', u'\n', u'\ r\n\t\t\t\tRoute\xa0des\xa04\xa0Vents', u'\r\n\t\t\t\t63810 Bagnols']

这是一个开始,但我需要重新爱上所有的空格和不必要的字符。我尝试使用.strip().strings.stripped_strings,但它不起作用。例子:

for a_tag in classActorboxLink.strings

for a_tag in classActorboxLink.stripped_strings

print a_tag.find_all_next(string=True, limit=5).strip() 

对于所有三个我得到:

AttributeError: 'ResultSet' object has no attribute 'strings/stripped_strings/strip'

【问题讨论】:

    标签: python html parsing beautifulsoup html-parsing


    【解决方案1】:

    找到h4 元素并使用find_next_siblings()

    h4s = soup.find_all("h4", class_="actorboxLink")
    for h4 in h4s:
        for text in h4.find_next_siblings(text=True):
            print(text.strip())
    

    【讨论】:

    • 这给了我这个错误:AttributeError: 'ResultSet' object has no attribute 'find_next_siblings'
    【解决方案2】:

    如果您不需要在不同变量中查找的 3 个元素中的每一个,您可以使用 &lt;div&gt; 上的 get_text() 函数将它们全部放在一个字符串中。如果还有其他div 标签,但它们都有类,您可以找到所有&lt;div&gt;class=false。如果您无法隔离您感兴趣的&lt;div&gt;,那么此解决方案将不适合您。

    import urllib
    from bs4 import BeautifulSoup    
    data = urllib.urlopen(url).read()
    soup = BeautifulSoup(data, "html.parser")
    
    for name in soup.find_all("div", class=false)
         print name.get_text().strip()
    

    顺便说一句,这是 python 3 和 bs4

    【讨论】:

    • 好建议,但我无法隔离我感兴趣的
      ...太多了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多