Skip to main content
 首页 » 编程设计

python之selenium 通过 css 选择器获取元素

2025年05月04日16luoye11

我正在尝试从给定的每个 block 中获取用户详细信息

driver.get("https://www.facebook.com/public/karim-pathan")          
wait = WebDriverWait(driver, 10) 
li_link = [] 
for s in driver.find_elements_by_class_name('clearfix'): 
    print s 
    print s.find_element_by_css_selector('_8o._8r.lfloat._ohe').get_attribute('href') 
    print s.find_element_by_tag_name('img').get_attribute('src') 

它说:

unable to find element with css selector

任何明显的提示。

请您参考如下方法:

只是基于您未登录的假设的猜测。您正在获取所有类 clearfix 的异常原因,带有 ._8o._8r.lfloat._ohe 的元素不存在。所以您的代码没有达到所需的元素。无论如何,如果你试图获取结果的 href 和 img 来源,你不需要像 @leo.fcx 所建议的那样遍历所有 clearfix 原因,你的 css 不正确,尝试 leo 提供的 css,您可以获得预期的结果:

driver.get("https://www.facebook.com/public/karim-pathan")          
for s in driver.find_elements_by_css_selector('._8o._8r.lfloat._ohe'): // there didn't seemed to iterate over each class of clearfix 
    print s.get_attribute('href') 
    print s.find_element_by_tag_name('img').get_attribute('src') 

附言对任何语法感到抱歉,从未探索过 python 绑定(bind) :)