[英]Trying to click amazon Best Sellers Rank (Python)
您好,我正在嘗試單擊這些鏈接,但是當我嘗試單擊時
driver.find_element_by_xpath('//*[@id="productDetails_detailBullets_sections1"]/tbody/tr[6]/td/span/span[2]/a').click()
它的工作,但問題是每個項目都有不同的路徑和它的變化,它不適用於某些項目
這很容易,即使您沒有指定您想要哪個鏈接,只有從表格中所有不同的鏈接將您轉移到表格。
您需要使用定制的 xpath,例如
//*[@id="productDetails_detailBullets_sections1"]/tbody/tr[6]/td/span/span['+i+']/a'
我將在哪里成為 for 循環中的迭代器。 為了獲得價值,我使用了類似的東西
driver.find_elements_by_xpath('//*[@id="productDetails_detailBullets_sections1"]/tbody/tr[6]/td/span/span').size();
亞馬遜網頁有 3 個Best Sellers Rank條目。 一種有效的方法是收集所有三(3)個暢銷書的href
,將它們存儲在一個列表中,然后在單獨的選項卡中打開以進行抓取。 要構建列表,您必須為visibility_of_all_elements_located()
引入WebDriverWait ,您可以使用以下任一Locator Strategies :
使用CSS_SELECTOR
:
driver.get('https://www.amazon.com/dp/B074T6C4YS') print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table#productDetails_detailBullets_sections1 td>span>span a")))])
在一行中使用CSS_SELECTOR
:
driver.get('https://www.amazon.com/dp/B074T6C4YS') print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='productDetails_detailBullets_sections1']//td/span/span//a")))])
控制台 Output:
['https://www.amazon.com/gp/bestsellers/kitchen/ref=pd_zg_ts_kitchen', 'https://www.amazon.com/gp/bestsellers/kitchen/289857/ref=pd_zg_hrsr_kitchen', 'https://www.amazon.com/gp/bestsellers/kitchen/289862/ref=pd_zg_hrsr_kitchen']
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.