selenium通过css选择器获取元素

时间:2015-07-24 12:59:03

标签: python css selenium selenium-webdriver web-scraping

我正在尝试从每个块获取用户详细信息

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

它说:

  

无法找到带有css选择器的元素

任何提示都很明显。

3 个答案:

答案 0 :(得分:2)

由于您使用了该元素适用的所有类名,因此在CSS选择器的开头添加.应修复它。

试试这个:

s.find_element_by_css_selector('._8o._8r.lfloat._ohe')

而不是:

s.find_element_by_css_selector('_8o._8r.lfloat._ohe')

答案 1 :(得分:2)

添加@ leo.fcx指向选择器的内容wait for search results to become visible

wait.until(EC.visibility_of_element_located((By.ID, "all_search_results")))

答案 2 :(得分:2)

仅基于您未登录的假设进行猜测。您将获得所有类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')

P.S。对不起任何语法,从未探索过python绑定:)