如何使用 Selenium 和 Python 根据标签名称和属性查找 Web 元素
我正在尝试使用Selenium登录我的Instagram帐户。为此,我需要将我的用户名和密码填充到登录表单中。
用户名输入栏具有标签INPUT
和名称
等于用户名
。有没有一种方法可以仅使用name
属性和标签名来检索此输入栏?我知道我可以使用XPATH和类名称,但是我只想使用name
属性来执行此操作。
我尝试了下面的代码,但有错误。
代码:
username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")
print(username.get_attribute("class"))
输出:
File "d:\Personal\CS\Bots\Instabot\msg.py", line 17, in <module>
username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")
编辑:
我也尝试过类名称和XPATH,但它们不起作用
XPath:
username = driver.find_element(by = By.XPATH, value = '//*[@id="loginForm"]/div/div[1]/div/label/input')
print(username.get_attribute("class"))
class:
username = driver.find_element(by = By.CSS_SELECTOR, value = 'input._2hvTZ pexuQ zyHYP')
print(username.get_attribute("class"))
我在这里做错了什么?
I am trying to log into my Instagram account using Selenium. For that, I need to fill in my username and password into the login form.
The username input bar has the tag input
and the name
equal to username
. Is there a way to retrieve this input bar using only the name
attribute and the tag name? I know I can use the XPath and the class name, but I want to do this using the name
attribute only.
I tried the code below but got an error.
Code:
username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")
print(username.get_attribute("class"))
Output:
File "d:\Personal\CS\Bots\Instabot\msg.py", line 17, in <module>
username = driver.find_element(by = By.CSS_SELECTOR, value = "input[name = 'username']")
Edit:
I tried the class name and the XPath too but they don't work either
XPath:
username = driver.find_element(by = By.XPATH, value = '//*[@id="loginForm"]/div/div[1]/div/label/input')
print(username.get_attribute("class"))
Class:
username = driver.find_element(by = By.CSS_SELECTOR, value = 'input._2hvTZ pexuQ zyHYP')
print(username.get_attribute("class"))
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没看错。 电话号码、用户名或电子邮件
字段具有
姓名
> 设置为用户名。因此,要定位该元素,您可以使用以下任一定位器策略:
使用xpath:
由于该元素是一个交互式元素,因此非常适合定位您需要诱导的元素WebDriver等待 element_to_be_clickable() 并且您可以使用以下任一定位策略:
使用CSS_SELECTOR:
使用XPATH:
注意:您必须添加以下导入:
You saw it right. The Phone number, username, or email
<input>
field has thename
set as username.So to locate the element you can use either of the following Locator Strategies:
Using css_selector:
Using xpath:
As the element is an interactive element ideally to locate the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using CSS_SELECTOR:
Using XPATH:
Note : You have to add the following imports :