栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

不幸的是,当您尝试对包含多个类的类属性值进行正则表达式匹配时,

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,#  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 refrom bs4 import BeautifulSoupfrom bs4.builder._htmlparser import HTMLParserTreeBuilderclass MyBuilder(HTMLParserTreeBuilder):    def __init__(self):        super(MyBuilder, self).__init__()        # BeautifulSoup, please don't treat "class" specially        self.cdata_list_attributes["*"].remove("class")bs = """<a  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 named+$"))print(found_elements)

在这种情况下,正则表达式将

class
整体应用于属性值。


或者,您可以仅分析

xml
启用了功能的HTML (如果适用):

soup = BeautifulSoup(data, "xml")

您还可以使用CSS选择器,将所有元素与

name-single
class和以“ name”开头的类进行匹配:

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

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640895.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号