我试图编写一个 Selenium 机器人来在 twitch 中进行搜索。 我可以单击搜索栏,但无法向搜索栏发送任何值。
有什么问题吗?我工作了几个小时但无法解决我的问题。
这是我的代码:
from selenium import webdriver
#https://selenium-python.readthedocs.io/
from selenium.webdriver.common.keys import Keys
#from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Twitch:
def __init__(self):
self.browser = webdriver.Chrome()
def openTwitch(self):
self.browser.get("https://www.twitch.tv/")
self.browser.maximize_window()
try:
barClick = WebDriverWait(self.browser,10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/div/div[2]/nav/div/div[2]/div/div')))
barClick.click()
except:
print("Element not clickable")
try:
searchBar = WebDriverWait(self.browser,10).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="tw-2a283106145a4249e75c7a6787c01324"]')))
searchBar.send_keys("Xantares") #this area is not working..
searchBar.send_keys(Keys.ENTER)
except:
print("Element not writable")
twtch = Twitch()
twtch.openTwitch()
最佳答案
尽量不要随机生成 id,它们是不稳定的,因此在下次运行中您将无法到达该元素。
例如,您可以从 input
标记中获取引用,例如:
searchBar = WebDriverWait(self.browser, 10).until(EC.visibility_of_element_ located((By.XPATH,'(//input[@type="search"])[1]')))
浏览器中有一个强大的工具可以帮助您找到正确的选择器:
您应该按F12
,然后在Elements
选项卡中按CTRL + F
,它允许您在那里测试XPATH表达式。
问候。
关于python - 为什么我无法使用 Selenium 在 Python 中将 keys 发送到 Twitch 搜索栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206946/