Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python使用selenium在产品容器中定位产品ID?_Python_Selenium_Xpath_Css Selectors_Webdriverwait - Fatal编程技术网

如何使用python使用selenium在产品容器中定位产品ID?

如何使用python使用selenium在产品容器中定位产品ID?,python,selenium,xpath,css-selectors,webdriverwait,Python,Selenium,Xpath,Css Selectors,Webdriverwait,我试图在网站中抓取产品ID,而ID位于产品容器中。它不返回这样的元素: driver.find_element_by_class_name('na finger product-container') HTML: 我想要检索的属性是ids_值,在本例中是#300# 网站: 如果要使用@class作为标识符,请尝试按单个类名搜索 driver.find_element_by_class_name('product-container') 或者通过CSS选择器 driver.find_ele

我试图在网站中抓取产品ID,而ID位于产品容器中。它不返回这样的元素:

driver.find_element_by_class_name('na finger product-container')
HTML:


我想要检索的属性是
ids_值
,在本例中是
#300#

网站:


如果要使用
@class
作为标识符,请尝试按单个类名搜索

driver.find_element_by_class_name('product-container')
或者通过CSS选择器

driver.find_element_by_css_selector('.na.finger.product-container') 

您可能还需要实现所需的动态数据驱动程序。通过css选择器('.na.finger.product container')查找元素。获取属性('na-data')

返回

{“ids#u值”:[“#290#”],“ids#u键”:“项目类型#id”,“项目类型#id”:[“#290#”],“标记#id”:[“#4#”],“应用程序页面#部分#id”:10103,“应用程序页面#id”:10011}

谢谢大家

来解析标签

import json
elem=driver.find_element_by_css_selector('.na.finger.product-container').get_attribute('na-data')
myJSON = json.loads(elem)
print(myJSON["ids_value"])
输出

['#290#']       

要从所有
中提取
ids\u值
,您必须使用()导出所有元素的
可见性,并且您可以使用以下任一项:

  • 使用
    CSS\u选择器

    print([my_elem.get_attribute("na-data").split("#")[1] for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div[na-element='item'][na-module='product']")))])
    
  • 使用
    XPATH

    print([my_elem.get_attribute("na-data").split("#")[1] for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@na-element='item' and @na-module='product']")))])
    
  • 控制台输出:

    ['290', '291', '292', '295', '296', '297', '298', '299', '300', '302', '303', '305', '306', '307', '308', '309']
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

您想要哪个属性
na id
?我想要的属性是“ids_值”,即“#300#”。在这种情况下,发布a是一个好主意,这样其他用户可以粘贴您的代码并快速回答。可以使用“driver.find#element_by#css#选择器('.na.finger.product container')”找到单个产品div,但如何访问{“id_值”:“300”}在“na数据”中。获取_属性('na-data'),然后进行解析。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC