2015-11-08 92 views
3

下面是從這個鏈接一小塊的HTML here硒蟒蛇遞歸文本刮

<div class="price-view"> 
    <div class="price component component-3 clearfix list-and-sale-price"> 
    <div class="list-price float-left mR20px striken"> 
     <label>Was</label> 
     <div class="value">$250.00</div> 
    </div> 
    <div class="sale-price float-left"> 
     <label>Now</label> 
     <div class="value">$150.00</div> 
    </div> 
    </div> 
</div> 

我想拉價$ 150這種情況下,但我想同樣的代碼在this打印$ 575鏈接

<div class="price-view"> 
    <div class="price component component-3 clearfix"> 
    <div class="list-price float-left mR20px "> 
     <div class="value">$575.00</div> 
    </div> 
    </div> 
</div> 

由於顯而易見的原因,下面的xpath代碼將無法在多個實例中工作。

price = driver.find_element_by_xpath('//*[@id="saksBody"]/div[4]/div[1]/div[2]/div[1]/div[6]/div/div/div/div').text 

所以,我試圖尋找到這樣的代碼:

price = driver.find_element_by_class_name('value') 

但是,這是不夠具體。

是否有某種方法可以打印<div class="price-view">中的所有文本?然後我可以使用正則表達式來解決其餘問題。

此代碼似乎並沒有抓住標籤內的文本標籤

price = driver.find_element_by_class_name('price-view').text 

要非常具體,我想知道如何輸出:

Was$250.00Now$150.00 

$575.00 

分別爲第一和第二鏈接。

回答

0

在這兩種情況下,定價在DIVprice-view之間,因此我們使用CSS選擇器div.price-view來獲取外部元素。然後它會查看list-and-sale-price類是否存在。如果是這樣,那麼我們有一個清單和銷售價格,所以搶到銷售價格。無論哪種方式存在清單價格,所以我們抓住它。這樣你就不需要將這些片段進行regex。

priceView = driver.find_element_by_css_selector("div.price-view") 
if (priceView.find_elements_by_css_selector("div.list-and-sale-price")) 
    # there is a list and sale price, grab the sale price 
    salePrice = priceView.find_element_by_css_selector("div.sale-price > div.value")).text 
# in either case, grab the list price 
listPrice = priceView.find_element_by_css_selector("div.list-price > div.value")).text