美味的汤,如果类"包含"或正则表达式?

Pow*_*fee 19 python regex beautifulsoup web-scraping

如果我的班级名字经常不同,比如说:

listing-col-line-3-11 dpt 41
listing-col-block-1-22 dpt 41
listing-col-line-4-13 CWK 12
Run Code Online (Sandbox Code Playgroud)

通常我可以这样做:

for EachPart in soup.find_all("div", {"class" : "ClassNamesHere"}):
            print EachPart.get_text()
Run Code Online (Sandbox Code Playgroud)

有太多的类名可以在这里使用,所以其中一些是出来的.

我知道Python没有我通常会使用的".contains"但它确实有一个"in".虽然我还没有找到一种方法来融入它.

我希望有一种方法可以用正则表达式做到这一点.虽然我的Python语法真的让我失望但我一直在尝试变化:

regex = re.compile('.*listing-col-.*')
    for EachPart in soup.find_all(regex):
Run Code Online (Sandbox Code Playgroud)

但这似乎并没有成功.

mfi*_*tzp 24

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

以下将返回包含文本'listing-col-'的所有div元素class:

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


Wal*_*aad 11

Yu可以尝试以下方法:

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