美丽的汤,如果类“包含”或Regex?

2024-06-17 01:05:38 发布

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

如果我的类名经常不同,比如说:

listing-col-line-3-11 dpt 41
listing-col-block-1-22 dpt 41
listing-col-line-4-13 CWK 12

通常我可以:

for EachPart in soup.find_all("div", {"class" : "ClassNamesHere"}):
            print EachPart.get_text()

这里有太多的类名需要处理,所以有很多类名是不可用的。

我知道Python没有“.contains”,我通常会使用,但它有一个“in”。尽管我还没能想出一个办法来合并它。

我希望有办法用regex做到这一点。尽管我的Python语法再次让我失望,但我一直在尝试以下变体:

regex = re.compile('.*listing-col-.*')
    for EachPart in soup.find_all(regex):

但这似乎没什么用。


Tags: inforlinecolallfindblockregex
2条回答

你可以试试这个:

regex = re.compile('.*listing-col-.*')
for EachPart in soup.find_all("div", {"class" : regex}):
        print EachPart.get_text()

BeautifulSoup支持CSS selectors,允许您根据特定属性的内容选择元素。这包括contains的选择器*=

下面将返回所有具有包含文本“listing col-”的class属性的div元素:

for EachPart in soup.select('div[class*="listing-col-"]'):
    print EachPart.get_text()

相关问题 更多 >