[英]Why I can't send_keys to Twitch search bar in Python with Selenium?
I was trying to write a Selenium bot to search in twitch.我试图编写一个 Selenium 机器人来在 twitch 中进行搜索。 I can click the search bar but I can't send any value to the search bar.我可以单击搜索栏,但无法向搜索栏发送任何值。
what is the issue?这是什么问题? I worked for hours but can't fix my problem.我工作了几个小时,但无法解决我的问题。
This is my code:这是我的代码:
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()
Try not take random generated ids, they are volatile so in the next run you will not reach the element.尽量不要使用随机生成的 id,它们是不稳定的,因此在下一次运行中您将无法到达该元素。
For example you could take a reference from input
tag like:例如,您可以从input
标签中获取参考,例如:
searchBar = WebDriverWait(self.browser, 10).until(EC.visibility_of_element_located((By.XPATH,'(//input[@type="search"])[1]')))
There is a powerfool tool in the browser that can help you to find the right selector:浏览器中有一个 powerfool 工具可以帮助您找到正确的选择器:
You should press F12
, then in the Elements
tab, press CTRL + F
, it allows you to test the XPATH expressions there.您应该按F12
,然后在Elements
选项卡中,按CTRL + F
,它允许您在那里测试 XPATH 表达式。
Regards.问候。
Try insert the text inside input
tag.尝试在input
标签内插入文本。
Something is wrong with your locator, change with:您的定位器有问题,请更改:
searchBar = WebDriverWait(self.browser,10).until(EC.visibility_of_element_located((By.XPATH,'//div[@class="tw-relative"]//input[not(contains(@id, "hidden"))]')))
Are you sure this ID(tw-2a283106145a4249e75c7a6787c01324) is valid?您确定此 ID(tw-2a283106145a4249e75c7a6787c01324) 有效吗? It looks like it's some randomly generated id.它看起来像是一些随机生成的ID。 If you would like to do it hardway, set focus to it, and use Actions to send keys.如果您想硬着头皮去做,请将焦点设置在它上面,然后使用 Actions 发送密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.