2013-11-20 145 views
0
for products in self.br.find_elements_by_xpath("//*[@class='image']/a"): 
    self.urls.append(products.get_attribute("href")) 

此代碼將查找所有類的hrefs鏈接。通過XPath查找元素後退

我的問題是,網頁有變化的來源有時它可以是//*[@class='image']/a但有時//*[@class='newPrice']/a。如果第一個xpath選項沒有找到任何東西,我怎樣才能將for循環更改爲使用其他表達式?

回答

3

存儲在一個變量輸出第一:

links = self.br.find_elements_by_xpath("//*[@class='image']/a") 
if not links: 
    links = self.br.find_elements_by_xpath("//*[@class='newPrice']/a") 
for products in links: 
    self.urls.append(products.get_attribute("href")) 
+0

完美的作品就像一個魅力! –

1

不等同於回退,但你可以使用一個或句法:

for products in self.br.find_elements_by_xpath(
     "//*[@class='image']/a | //*[@class='newPrice']/a"): 
    self.urls.append(products.get_attribute("href")) 
+0

謝謝我真的很喜歡這可以很容易使用:) –

相關問題