GVKun编程网logo

如何使用BeautifulSoup在两个指定标签之间获取所有文本?(beautifulsoup获取标签内容)

9

在这篇文章中,我们将带领您了解如何使用BeautifulSoup在两个指定标签之间获取所有文本?的全貌,包括beautifulsoup获取标签内容的相关情况。同时,我们还将为您介绍有关Beautifu

在这篇文章中,我们将带领您了解如何使用BeautifulSoup在两个指定标签之间获取所有文本?的全貌,包括beautifulsoup获取标签内容的相关情况。同时,我们还将为您介绍有关BeautifulSoup-获取所有文本,但保留链接html?、Learn Beautiful Soup(5) —— 使用BeautifulSoup改变网页内容、python BeautifulSoup怎么获取无标签文本?、使用 BeautifulSoup 提取不在标签之间的文本的知识,以帮助您更好地理解这个主题。

本文目录一览:

如何使用BeautifulSoup在两个指定标签之间获取所有文本?(beautifulsoup获取标签内容)

如何使用BeautifulSoup在两个指定标签之间获取所有文本?(beautifulsoup获取标签内容)

html = """...<tt>all</tt><big>(</big><em>iterable</em><big>)</big><ahref="#all" title="Permalink to this definition">¶</a>..."""

我想获取从开始标记big到第一次出现a标记之前的所有文本。这意味着,如果我举这个例子,那么我必须(iterable)以字符串形式获取。

答案1

小编典典

我会避免使用nextSibling,因为从您的问题开始,您想要包括直到next的所有内容<a>,而不管它是在同级元素,父元素还是子元素中。

因此,我认为最好的方法是找到下一个<a>元素的节点,然后递归循环,直到出现为止,然后添加遇到的每个字符串。如果您的HTML与示例大不相同,则可能需要整理以下内容,但是这样的工作应该可以:

from bs4 import BeautifulSoup#by taking the `html` variable from the question.html = BeautifulSoup(html)firstBigTag = html.find_all(''big'')[0]nextATag = firstBigTag.find_next(''a'')def loopUntilA(text, firstElement):    text += firstElement.string    if (firstElement.next.next == nextATag):                     return text    else:        #Using double next to skip the string nodes themselves        return loopUntilA(text, firstElement.next.next)targetString = loopUntilA('''', firstBigTag)print targetString

BeautifulSoup-获取所有文本,但保留链接html?

BeautifulSoup-获取所有文本,但保留链接html?

我必须处理一个非常混乱的HTML大型存档,其中充满了多余的表,跨度和内联样式到markdown中。

我正在尝试使用BeautifulSoup来完成此任务,而我的目标基本上是该get_text()函数的输出,除了href完整保留锚标签外。

例如,我要转换:

<td>    <font><span>Hello</span><span>World</span></font><br>    <span>Foo Bar <span>Baz</span></span><br>    <span>Example Link: <a href="https://google.com" target="_blank">Google</a></span></td>

进入:

Hello WorldFoo Bar BazExample Link: <a href="https://google.com">Google</a>

到目前为止,我的思考过程是简单地获取所有标签,如果它们不是锚,则将它们全部解包,但这会导致文本被重复多次,因为soup.find_all(True)递归嵌套的标签作为单独的元素返回:

#!/usr/bin/env pythonfrom bs4 import BeautifulSoupexample_html = ''<td><font><span>Hello</span><span>World</span></font><br><span>Foo Bar <span>Baz</span></span><br><span>Example Link: <a href="https://google.com" target="_blank">Google</a></span></td>''soup = BeautifulSoup(example_html, ''lxml'')tags = soup.find_all(True)for tag in tags:    if (tag.name == ''a''):        print("<a href=''{}''>{}</a>".format(tag[''href''], tag.get_text()))    else:        print(tag.get_text())

当解析器在树中向下移动时,它将返回多个片段/重复项:

HelloWorldFoo Bar BazExample Link: GoogleHelloWorldFoo Bar BazExample Link: GoogleHelloWorldFoo Bar BazExample Link: GoogleHelloWorldHelloWorldFoo Bar BazBazExample Link: Google<a href=''https://google.com''>Google</a>

答案1

小编典典

解决此问题的一种可能方法a是在打印出元素文本时对元素进行一些特殊处理。

您可以通过重写_all_strings()方法并返回a后代元素的字符串表示形式并跳过a元素内的可导航字符串来实现。遵循以下原则:

from bs4 import BeautifulSoup, NavigableString, CData, Tagclass MyBeautifulSoup(BeautifulSoup):    def _all_strings(self, strip=False, types=(NavigableString, CData)):        for descendant in self.descendants:            # return "a" string representation if we encounter it            if isinstance(descendant, Tag) and descendant.name == ''a'':                yield str(descendant)            # skip an inner text node inside "a"            if isinstance(descendant, NavigableString) and descendant.parent.name == ''a'':                continue            # default behavior            if (                (types is None and not isinstance(descendant, NavigableString))                or                (types is not None and type(descendant) not in types)):                continue            if strip:                descendant = descendant.strip()                if len(descendant) == 0:                    continue            yield descendant

演示:

In [1]: data = """   ...: <td>   ...:     <font><span>Hello</span><span>World</span></font><br>   ...:     <span>Foo Bar <span>Baz</span></span><br>   ...:     <span>Example Link: <a href="https://google.com" target="_blank">Google</a></span>   ...: </td>   ...: """In [2]: soup = MyBeautifulSoup(data, "lxml")In [3]: print(soup.get_text())HelloWorldFoo Bar BazExample Link: <a href="https://google.com"target="_blank">Google</a>

Learn Beautiful Soup(5) —— 使用BeautifulSoup改变网页内容

Learn Beautiful Soup(5) —— 使用BeautifulSoup改变网页内容

BeautifulSoup除了可以查找和定位网页内容,还可以修改网页。修改意味着可以增加或删除标签,改变标签名字,变更标签属性,改变文本内容等等。

 使用修BeautifulSoup修改标签

每一个标签在BeautifulSoup里面都被当作一个标签对象,这个对象可以执行以下任务:

  • 修改标签名
  • 修改标签属性
  • 增加新标签
  • 删除存在的标签
  • 修改标签的文本内容

修改标签的名字

只需要修改.name参数就可以修改标签名字。

producer_entries.name = "div"<span>怎么办嘛</span><img src="file:///C:\Users\ADMINI~1\AppData\Local\Temp\~LWHD)}S}%DE5RTOO[CVEI1.gif" sysface="15"alt="" />

你咋这么说 


修改标签的属性

修改标签的属性如class,id,style等。因为属性以字典形式储存,所以改变标签属性就是简单的处理python的字典。

更新已经存在属性的标签

可以参照如下代码:

producer_entries[''id'']="producers_new_value"

为一个标签增加一个新的属性

比如一个标签没有class属性,那么可以参照如下代码增加class属性,

producer_entries[''class'']=''newclass''

删除标签属性

使用del操作符,示例如下:

del producer_entries[''class'']

增加一个新的标签

BeautifulSoup有new_tag()方法来创造一个新的标签。然后可以使用append(),insert(),insert_after()或者insert_before()等方法来对新标签进行插入。

增加一个新生产者,使用new_tag()然后append()

参照前面例子,生产者除了plants和alage外,我们现在添加一个phytoplankton.首先,需要先创造一个li标签。

用new_tag()创建一个新标签

new_tag()方法只能用于BeautifulSoup对象。现在创建一个li对象。

soup = BeautifulSoup(html_markup,"lxml")
new_li_tag = soup.new_tag("li")

new_tag()对象必须的参数是标签名,其他标签属性参数或其他参数都是可选参数。举例:

new_atag=soup.new_tag("a",href="www.example.com")

new_li_tag.attrs={''class'':''producerlist''}


使用append()方法添加新标签

append()方法添加新标签于,contents之后,就跟Python列表方法append()一样。

producer_entries = soup.ul
producer_entries.append(new_li_tag)

li标签是ul标签的子代,添加新标签后的输出结果。

<ul id="producers">
<li>
<div>
plants
</div>
<div>
100000
</div>
</li>
<li>
<div>
algae
</div>
<div>
100000
</div>
</li>s
<li>
</li>

</ul>

使用insert()向li标签中添加新的div标签

append()在.contents之后添加新标签,而insert()却不是如此。我们需要指定插入的位置。就跟python中的Insert()方法一样。

new_div_name_tag=soup.new_tag("div")
new_div_name_tag["class"]="name"
new_div_number_tag=soup.new_tag("div")
new_div_number_tag["class"]="number"

先是创建两个div标签

new_li_tag.insert(0,new_div_name_tag)
new_li_tag.insert(1,new_div_number_tag)
print(new_li_tag.prettify())

然后进行插入,输出效果如下:

<li class_="producerlist">
<div>
</div>
<div>
</div>

</li>

改变字符串内容

在上面例子中,只是添加了标签,但标签中却没有内容,如果想添加内容的话,BeautifulSoup也可以做到。

使用.string修改字符串内容

比如:

new_div_name_tag.string="phytoplankton"
print(producer_entries.prettify())
输出如下:

<ul id="producers">
<li>
<div>
plants
</div>
<div>
100000
</div>
</li>
<li>
<div>
algae
</div>
<div>
100000
</div>
</li>
<li>
<div>
phytoplankton
</div>

<div>
</div>
</li>
</ul>

使用.append/(),insert(),和new_string()添加字符串

使用append()和insert()的效果就跟用在添加新标签中一样。比如:

new_div_name_tag.append("producer")
print(soup.prettify())

输出:

<html>
<body>
<div>
<ul id="producers">
<li>
<div>
plants
</div>
<div>
100000
</div>
</li>
<li>
<div>
algae
</div>
<div>
100000
</div>
</li>
<li>
<strong><div>
phytoplankton
producer
</div>
</strong><div>
</div>
</li>
</ul>
</div>
</body>
</html>


还有一个new_string()方法,

new_string_toappend = soup.new_string("producer")
new_div_name_tag.append(new_string_toappend)

从网页中删除一个标签

删除标签的方法有decomose()和extract()方法


使用decompose()删除生产者


我们现在移去属性的div标签,使用decompose()方法。

third_producer = soup.find_all("li")[2]
div_name = third_producer.div
div_name.decompose()
print(third_producer.prettify())

输出:

<li class_="producerlist">
<div class_="number">
10000
</div>

</li>

decompose()方法会移去标签及标签的子代。

使用extract()删除生产者

extract()用于删除一个HTMNL文档中昂的标签或者字符串,另外,它还返回一个被删除掉的标签或字符串的句柄。不同于decompose(),extract也可以用于字符串。

third_producer_removed=third_producer.extract()
print(soup.prettify())


使用BeautifulSoup删除标签的内容

标签可以有一个NavigableString对象或tag对象作为子代。删除掉这些子代可以使用clear()

举例,可以移掉带有plants的div标签和 相应的class=number属性标签。

li_plants=soup.li

li_plants.clear()

输出:

<li></li>

可以看出跟li相关的标签内容被删除干净。


修改内容的特别函数

除了我们之前看到的那些方法,BeautifulSoup还有其他修改内容的方法。

  • Insert_after()和Insert_before()方法:

这两个方法用于在标签或字符串之前或之后插入标签或字符串。这个方法需要的参数只有NavigavleString和tag对象。

soup = BeautifulSoup(html_markup,"lxml")
div_number = soup.find("div",class_="number")
div_ecosystem = soup.new_tag("div")
div_ecosystem[''class''] = "ecosystem"
div_ecosystem.append("soil")
div_number.insert_after(div_ecosystem)
print(soup.prettify())

输出:

<html>
<body>
<div>
<ul id="producers">
<li>
<div>
plants
</div>
<div>
100000
</div>
<div>
soil
</div>

</li>
<li>
<div>
algae
</div>

<div>
100000
</div>
</li>
</ul>
</div>
</body>
</html>


  • replace_with()方法:

这个方法用于用一个新的标签或字符串替代原有的标签或字符串。这个方法把一个标签对象或字符串对象作为输入。replace_with()会返回一个被替代标签或字符串的句柄。

soup = BeautifulSoup(html_markup,"lxml")
div_name =soup.div
div_name.string.replace_with("phytoplankton")
print(soup.prettify())

replace_with()同样也可以用于完全的替换掉一个标签。

  • wrap()和unwrap()方法:

wrap()方法用于在一个标签或字符串外包裹一个标签或字符串。比如可以用一个div标签包裹li标签里的全部内容。

li_tags = soup.find_all("li")
for li in li_tags:
<span>	</span>new_divtag = soup.new_tag("div")
<span>	</span>li.wrap(new_divtag)
print(soup.prettify())


而unwrap()就跟wrap()做的事情相反。unwrap()和replace_with()一样会返回被替代的标签句柄。



python BeautifulSoup怎么获取无标签文本?

python BeautifulSoup怎么获取无标签文本?

<p>aaa</p>bbb
<p>ccc</p>ddd

怎么获取bbb和ddd呢?

使用 BeautifulSoup 提取不在标签之间的文本

使用 BeautifulSoup 提取不在标签之间的文本

如何解决使用 BeautifulSoup 提取不在标签之间的文本?

我正在通过抓取 imdb.com 来练习 BeautifulSoup 并且对于我想要的给定演员

  1. 获取他们作为演员出演的所有电影的列表;
  2. 过滤我们所有的非全长电影,即电视剧、短片、短片等。

到目前为止,对于所有电影,我都能得到类似以下汤的东西:

<divid="actor-tt14677742">
    <span>2021</span>
    <b><a href="/title/tt14677742/">Welcome Back Future</a></b>
     (Short)
    <br/>
     Leo
</div>

正如我们所见,这部电影应该被过滤掉,因为它很短。我们还可以看到有关 (Short) 的信息没有包含在任何标签中。
因此,我的问题:
我如何从汤中获取这些信息,如果有的话我如何在</b>之后查找一些信息?

解决方法

你可以使用这个:

from bs4 import BeautifulSoup as bs

HTML="""<divid="actor-tt14677742">
    <span>2021</span>
    <b><a href="/title/tt14677742/">Welcome Back Future</a></b>
     (Short)
    <br/>
     Leo
</div>
"""

soup=bs(HTML,"lxml")

print(soup.find("div").find_all(text=True,recursive=False))
# [''\n'',''\n'',''\n     (Short)\n    '',''\n     Leo\n'']

# If you use html5lib as parse then answer is a bit different:
soup=bs(HTML,"html5lib")
print(soup.find("div").find_all(text=True,recursive=False))
# [''\n    '',''\n    '',''\n     Leo\n'']

# If you want all of the text from div then try this:
print(soup.find("div").find_all(text=True,recursive=True))
# [''\n'',''2021'',''Welcome Back Future'',''\n     Leo\n'']
# Or simply use
print(soup.find("div").text)
"""
2021
Welcome Back Future
     (Short)

     Leo

"""

我想你现在可以清理它了,我相信得到他们作为演员出演的所有电影的列表;意味着你还需要Leo

,

顺便说一句,我不确定你在找什么。但基于评论和其他答案。

下面应该可以实现您的目标。

from bs4 import BeautifulSoup


html = ''''''<divid="actor-tt14677742">
    <span>2021</span>
    <b><a href="/title/tt14677742/">Welcome Back Future</a></b>
     (Short)
    <br/>
     Leo
</div>''''''


soup = BeautifulSoup(html,''lxml'')
print(list(soup.select_one(''.filmo-row'').stripped_strings))

输出:

[''2021'',''(Short)'',''Leo'']
,

我对 bs4 了解不多,但不知何故寻找 next_sibling 并解决了我的问题。

所以我这样做:

category = movie_soup.find_all(''b'')[0].next_sibling
if ''TV'' in category or ''Short'' in category or ''Series'' in category or ''Video'' in category or ''Documentary'' in category:
    return None,None

如果我发现我不需要的电影因为它属于我不需要的类别之一,我将返回 None、None。我知道这不是最好的代码风格,但它对我有用。

我们今天的关于如何使用BeautifulSoup在两个指定标签之间获取所有文本?beautifulsoup获取标签内容的分享已经告一段落,感谢您的关注,如果您想了解更多关于BeautifulSoup-获取所有文本,但保留链接html?、Learn Beautiful Soup(5) —— 使用BeautifulSoup改变网页内容、python BeautifulSoup怎么获取无标签文本?、使用 BeautifulSoup 提取不在标签之间的文本的相关信息,请在本站查询。

本文标签: