python - 为什么我无法使用 Selenium 在 Python 中将 keys 发送到 Twitch 搜索栏?

标签 python python-3.x selenium selenium-webdriver

我试图编写一个 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]')))

浏览器中有一个强大的工具可以帮助您找到正确的选择器:

Browser Console

您应该按F12,然后在Elements选项卡中按CTRL + F,它允许您在那里测试XPATH表达式。

问候。

关于python - 为什么我无法使用 Selenium 在 Python 中将 keys 发送到 Twitch 搜索栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206946/

相关文章:

python - 在困惑的能源数据中寻找层次结构

python - 如何从 Wagtail modeladmin 中的帮助面板访问实例?

python - 使用 python 将 .txt 文件(在同一目录中)合并为一个主 .txt 文件

python - 相对导入需要 'package' 参数

python - if __name__ == '__main__' : statement 下写很多代码是不是很常见

java - 使用selenium时如何关闭windows文件上传窗口

c# - BrowserStack:意外错误。需要授权

python-3.x - 基于 Pandas 中的另一个数据框计算多列的加权平均结果

python - 正则表达式 Python 问题

linux - 我们可以从 Linux 终端运行 Selenium WebDriver 代码的 Jar 文件吗?如何?