t seem to have a Chinese version BeautifulSoup4文档示例似乎没有中文版本

2024-04-29 04:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我是美团4的新手,学习非常刻苦。问题在于下一段代码(我在https://www.crummy.com/software/BeautifulSoup/bs4/doc/页的文档中找到了它,这篇文章是关于函数定义的):

  def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')     (A)
  soup.find_all(has_class_but_no_id)

我希望得到这样的结果(见文档):

  # [<p class="title"><b>The Dormouse's story</b></p>,
  #  <p class="story">Once upon a time there were...</p>,       (B)
  #  <p class="story">...</p>]  

但我得到了下一个结果:

  [<p class="title"><b>The Dormouse's story</b></p>, <p class="story">Once 
  upon a time there were three little sisters; and their names were
  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,                     
  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; 
  and they lived at the bottom of a well.</p>, <p class="story">...</p>]

我查看了文档,发现只有.has\u attr方法被弃用。没有更多细节。如何更改初始代码(A)以获得预期结果(B)?有人能帮忙解决这个问题吗?泰恩。你知道吗


Tags: and代码文档comidhttpexampletag
2条回答

医生说:

This function only picks up the 'p' tags.It doesn’t pick up the 'a' tags, because those tags define both “class” and “id”. It doesn’t pick up tags like 'html' and 'title', because those tags don’t define “class”.

 soup.find_all(has_class_but_no_id)
# [<p class="title"><b>The Dormouse's story</b></p>,
#  <p class="story">Once upon a time there were...</p>,
#  <p class="story">...</p>]

这是不清楚的,它导致人们期待一个没有任何结果标签。他们应该更改语句或示例。你知道吗

它起作用了。 您必须注意,列表中的第二个结果没有检查内部标记(子标记)中的相同条件。所以包装<p class="story">已经满足了条件,并且已经和它的所有内容一起放在结果列表中。你知道吗

此结果列表:

[<p class="title"><b>The Dormouse's story</b></p>,
             -
 <p class="story">Once 
      upon a time there were three little sisters; and their names were
      <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
      <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
      <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; 
      and they lived at the bottom of a well.</p>,
             -
 <p class="story">...</p>]

包含三个标记,每个项都有'class'属性,没有'id'属性。你知道吗

相关问题 更多 >