当前位置: 首页 > 面试题库 >

通过复合类名称搜索时,BeautifulSoup返回空列表

易波涛
2023-03-14
问题内容

当使用正则表达式按复合类名称搜索时,BeautifulSoup返回空列表。

例:

import re
from bs4 import BeautifulSoup

bs = 
    """
    <a class="name-single name692" href="www.example.com"">Example Text</a>
    """

bsObj = BeautifulSoup(bs)

# this returns the class
found_elements = bsObj.find_all("a", class_= re.compile("^(name-single.*)$"))

# this returns an empty list
found_elements = bsObj.find_all("a", class_= re.compile("^(name-single name\d*)$"))

我需要对课程的选择非常精确。有任何想法吗?


问题答案:

不幸的是,当您尝试对包含多个类的类属性值进行正则表达式匹配时,BeautifulSoup会将正则表达式分别应用于每个单个类。

这一切都是因为class是一个很特别的多值属性,每一次你解析HTML的一个BeautifulSoup的树建设者(取决于解析器选择)内部分裂从一个类的字符串值入类(报价列表HTMLTreeBuilder的docstring):

# The HTML standard defines these attributes as containing a
# space-separated list of values, not a single value. That is,
# class="foo bar" means that the 'class' attribute has two values,
# 'foo' and 'bar', not the single value 'foo bar'.  When we
# encounter one of these attributes, we will parse its value into
# a list of values if possible. Upon output, the list will be
# converted back into a string.

有多种解决方法,但这是一种hack-ish解决方案-
我们将通过制作简单的自定义树生成器来要求BeautifulSoup不要将其class作为多值属性来处理:

import re

from bs4 import BeautifulSoup
from bs4.builder._htmlparser import HTMLParserTreeBuilder


class MyBuilder(HTMLParserTreeBuilder):
    def __init__(self):
        super(MyBuilder, self).__init__()

        # BeautifulSoup, please don't treat "class" specially
        self.cdata_list_attributes["*"].remove("class")


bs = """<a class="name-single name692" href="www.example.com"">Example Text</a>"""
bsObj = BeautifulSoup(bs, "html.parser", builder=MyBuilder())
found_elements = bsObj.find_all("a", class_=re.compile(r"^name\-single name\d+$"))

print(found_elements)

在这种情况下,正则表达式将class整体应用于属性值。

或者,您可以仅分析xml启用了功能的HTML (如果适用):

soup = BeautifulSoup(data, "xml")

您还可以使用CSS选择器,将所有元素与name-singleclass和以“ name”开头的类进行匹配:

soup.select("a.name-single,a[class^=name]")

然后,您可以根据需要手动应用正则表达式:

pattern = re.compile(r"^name-single name\d+$")
for elm in bsObj.select("a.name-single,a[class^=name]"):
    match = pattern.match(" ".join(elm["class"]))
    if match:
        print(elm)


 类似资料:
  • 问题内容: 目标:按编号从PHP对象中检索数据元素。 这是对象的print_r($ data): 我不知道如何从中获取价值。这只是多记录对象的一条记录,应该使用id而不是名称。 这些是尝试失败的尝试,以说明目标是什么: 问题答案: 通常,PHP变量名称不能以数字开头。您也不能像未实现那样将其作为数组访问-这只是一个普通的基类。 但是,在这种情况下,您可以尝试按其数字名称访问对象属性,如下所示: 我

  • 我用java编写了一个实用的二叉搜索树,除了一个关键的函数,搜索。我使用的逻辑是,我将检查根是否为空,然后我要搜索的术语是否等于根(所以返回根)或>根(所以搜索右子树)或 使用printlns查看正在发生的事情,我发现如果值在那里,它将通过正确的if语句(包括将BNode n设置为找到的值),但随后由于某种原因将再次通过方法(返回null)。 这个方法唯一起作用的时候是在搜索根节点的时候,这对我来

  • 我使用ant作为构建工具,并使用Ivy进行依赖管理。 现在,当我给蚂蚁构建时,它找不到罐子,问题是它正在附加linux-x86_64。它正在寻找下面的罐子 超文本传输协议://companyRepo: 8081/nexus/Content/group/官方开发/io/netty/netty-transport-nate-epol/4.1.48。最终/netty-运输-本地-电子投票-4.1.48。

  • 我有一个包含2列store_number和manager_id的表,我为这个表创建了一个实体和一个存储库类。 它返回一个空列表,但是当我直接执行上面的查询时,我会得到结果。 请帮我做这个。我在这里做错什么了吗?

  • 问题内容: 我正在使用driver.findelement by.classname方法在firefox浏览器上读取元素,但是我收到“不支持复合类名。请考虑搜索一个类名并过滤结果。” 例外 这是我的代码 问题答案: 不,就您的问题而言,您自己的答案并不是最好的答案。 假设您有这样的HTML: 会找到两个,然后返回您的第一个,而不是您想要的一个。您真正想要的是,但是就像您在问题中说的那样,这将不起作

  • 我是Android开发的新手,下面是我的关于使用Geocoder获取当前位置的城市名称的代码,它返回空: private void updateCurrentLocation(Location Location){double lat=0.0,lng=0.0; 有谁能帮忙吗?谢谢你!顺便说一句,有没有更好的办法来接收一个城市名字?谢谢你!