2017-06-27 77 views
0

你好,我有試圖找到利用硒與Python的東西聯繫的幾個問題匹配鏈接[硒]

<a class="name-link" 
href="/shop/accessories/wyqibr8gd/h8vy9fid4">Supreme®/Hanes® Crew Socks (4 
Pack)</a> 

<a class="name-link" href="/shop/accessories/wyqibr8gd/h8vy9fid4">Black</a> 

我所試圖做的就是鏈接的頂級產品和脫脂通過並將其與黑色的顏色鏈接相匹配

我目前迷路了,我的所有想法都沒有解決。如果你有任何想法,請讓我知道

回答

0

這是Java,但邏輯可以被重用 -

//Get the list of all the links 
List<WebElement> allLinks = driver.findElements(By.xpath("//a")); 

//Get the href from the first link 
String hrefFirstLink = allLinks.get(0).getAttribute("href"); 

//Search all the links for find the href again 
for(int i=1; i<allLinks.size(); i++) { //loop from 1 as index 0 has the same link 
    if(allLinks.get(i).getAttribute("href").equals(hrefFirstLink)) { 
    String color = allLinks.get(i).getAttribute("text"); 
    System.out.println(color); // this would print Black 
    break; 
    } 
} 
0

邏輯蟒蛇

records = driver.find_elements_by_xpath('//a') 

    for record in records: 
    print record.text 
0

我會發現所有的鏈接關聯的類「名稱鏈接」(其他答案將拉動所有鏈接),然後構建與每個鏈接關聯的WebElements地圖。這裏有一些(醜陋的)代碼可以實現這一點,生成一個字典,其中的關鍵字是產品名稱和顏色之間常見的url的標準化版本,並且該值是具有該公共url的鏈接列表:

name_link_elements = self.driver.find_elements_by_css_selector('a.name-link') 

    product_links = {} 
    for link_element in name_link_elements: 
     href = link_element.get_attribute('href') 
     key = urlparse.urlparse(href).path.replace("/", "_") 
     if key not in product_links.keys(): 
      product_links[key] = {} 
     if 'products' not in product_links[key].keys(): 
      product_links[key]['products'] = [] 
     product_links[key]['href'] = href 
     product_links[key]['products'].append(link_element) 

    print product_links