相关疑难解决方法(0)

禁用特殊的"类"属性处理

故事:

解析HTML时BeautifulSoup,class属性被视为多值属性,并以特殊方式处理:

请记住,单个标记的"class"属性可以有多个值.当您搜索与某个CSS类匹配的标记时,您将匹配其任何CSS类.

此外,作为其他树构建器类的基础HTMLTreeBuilder使用的内置引用BeautifulSoup,例如,HTMLParserTreeBuilder:

# 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 …
Run Code Online (Sandbox Code Playgroud)

html python beautifulsoup html-parsing

15
推荐指数
1
解决办法
379
查看次数

Beautiful Soup的Python正则表达式

我使用Beautiful Soup来提取特定的div标签,似乎我不能使用简单的字符串匹配.

该页面有一些标签形式

<div class="comment form new"...> 
Run Code Online (Sandbox Code Playgroud)

我想忽略它,还有一些标签的形式

<div class="comment comment-xxxx..."> 
Run Code Online (Sandbox Code Playgroud)

其中x表示任意长度的整数,椭圆表示由空格分隔的任意数量的其他值(我不关心).我无法弄清楚正确的正则表达式,特别是因为我从未使用过python的re class.

运用

soup.find_all(class_="comment") 
Run Code Online (Sandbox Code Playgroud)

查找以单词comment开头的所有标签.我试过用

soup.find_all(class_=re.compile(r'(comment)( )(comment)'))
soup.find_all(class_=re.compile(r'comment comment.*'))
Run Code Online (Sandbox Code Playgroud)

还有很多其他变种,但我想我在这里遗漏了一些关于正则表达式或match()如何工作的东西.谁能帮我吗?

python regex beautifulsoup

5
推荐指数
1
解决办法
1万
查看次数

Beautifulsoup 如何找到所有工作

我注意到findAll's 方法的一些奇怪行为:

>>> htmls="<html><body><p class=\"pagination-container\">slytherin</p><p class=\"pagination-container and something\">gryffindor</p></body></html>"
>>> soup=BeautifulSoup(htmls, "html.parser")
>>> for i in soup.findAll("p",{"class":"pagination-container"}):
    print(i.text)


slytherin
gryffindor
>>> for i in soup.findAll("p", {"class":"pag"}):
    print(i.text)


>>> for i in soup.findAll("p",{"class":"pagination-container"}):
    print(i.text)


slytherin
gryffindor
>>> for i in soup.findAll("p",{"class":"pagination"}):
    print(i.text)


>>> len(soup.findAll("p",{"class":"pagination-container"}))
2
>>> len(soup.findAll("p",{"class":"pagination-containe"}))
0
>>> len(soup.findAll("p",{"class":"pagination-contai"}))
0
>>> len(soup.findAll("p",{"class":"pagination-container and something"}))
1
>>> len(soup.findAll("p",{"class":"pagination-conta"}))
0
Run Code Online (Sandbox Code Playgroud)

因此,当我们搜索pagination-container它时,它会返回第一个和第二个p标签。这让我觉得它寻找部分平等:类似于if passed_string in class_attribute_value:. 所以我缩短了findAll方法中的字符串,它从来没有找到任何东西!

这怎么可能?

html python beautifulsoup html-parsing

3
推荐指数
1
解决办法
5819
查看次数

标签 统计

beautifulsoup ×3

python ×3

html ×2

html-parsing ×2

regex ×1