【问题标题】:Selenium - cannot find youtube search barSelenium - 找不到 youtube 搜索栏
【发布时间】:2020-08-04 07:48:24
【问题描述】:

错误信息:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: input.ytd-searchbox

我不断收到此错误,即使我从其他解决方案中添加了一个睡眠命令以使页面使用 javascript 动态加载,但它仍然找不到它?

import time
from selenium import webdriver  
firefox = webdriver.Firefox()
firefox.get("https://www.youtube.com")
element = firefox.find_element_by_css_selector("ytd-mini-guide-entry-renderer.style-scope:nth-child(3) > a:nth-child(1)") # opens subscriptions
element.click()
time.sleep(10) # wait for page to load before finding it
searchelement = firefox.find_element_by_css_selector('input.ytd-searchbox') # search bar

searchelement.send_keys("Cute Puppies")
searchelement.submit()

【问题讨论】:

标签: python selenium web-scraping time youtube


【解决方案1】:

我刚刚更改了 CSS 选择器。你在这里做错了。 嗯……我是怎么做到的?好吧,选择 CSS 选择器有一个简单的技巧。

  1. 首先输入标签名称。在您的情况下,它是input
  2. 如果此处存在ID,请输入带有# 的ID 名称。所以 和我一样:#search
  3. 如果那里有class,则在其名称前使用.。为了 例如.search

试试这个。它正在工作:

import time
from selenium import webdriver  
firefox = webdriver.Firefox(executable_path=r'C:\Users\intel\Downloads\Setups\geckodriver.exe')
firefox.get("https://www.youtube.com")
element = firefox.find_element_by_css_selector(".style-scope:nth-child(1) > #items > .style-scope:nth-child(3) > #endpoint .title") # opens subscriptions
element.click()
time.sleep(10) # wait for page to load before finding it
searchelement = firefox.find_element_by_css_selector('input#search') # search bar

searchelement.send_keys("Cute Puppies")
searchelement.submit()

【讨论】:

  • 为什么当我使用搜索框的inspect元素时css选择器不起作用?
  • 当我使用检查复制选择器时,它只返回了#search。但这里没有必要变得复杂。如果将来您遇到 CSS Selectors 问题,请使用此 chrome 扩展:chrome.google.com/webstore/detail/get-unique-css-selector/…@MahdeenSky
  • 太有用了
猜你喜欢
  • 2020-12-15
  • 1970-01-01
  • 2018-10-07
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多