2016-01-07 36 views
5

如果我的類名稱,例如經常是不同的說:美麗的湯,如果類「包含」或正則表達式?

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」。雖然我還沒有找到一種方法來整合這一點。

我希望有一種方法可以用正則表達式來實現。雖然我的Python語法再次讓我失望我一直在嘗試變化:

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

但是,這似乎並沒有這樣做。

回答

6

BeautifulSoup支持CSS selectors它允許您根據特定屬性的內容選擇元素。這包括用於包含的選擇器*=

下面將返回所有div元素包含文本「上市-同事」一class屬性:

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

鬱可試試這個:

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