尝试单击亚马逊畅销书排行榜(Python)

2024-10-03 21:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试单击这些链接,但当我尝试使用

driver.find_element_by_xpath('//*[@id="productDetails_detailBullets_sections1"]/tbody/tr[6]/td/span/span[2]/a').click()

它的工作,但问题是每个项目都有不同的路径和它的变化,它不适用于某些项目

网址:https://www.amazon.com/MICHELANGELO-Piece-Rainbow-Kitchen-Knife/dp/B074T6C4YS/ref=zg_bs_289857_1?_encoding=UTF8&psc=1&refRID=K5GAX1GF2SDZMN3NS403>

enter image description here


Tags: 项目idby链接driverelementfindxpath
2条回答

{a1}有3个条目用于畅销书排名。一种有效的方法是收集所有三(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")))])
    
  • 控制台输出:

    ['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
    

这很简单,即使您没有指定要使用哪个链接,也只是从表中选择了将您传输到表的所有不同链接

您需要使用定制的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();

相关问题 更多 >