DrWhiter 发表于 2021-8-8 15:07:34

关于selenium定位元素的问题

我试着运行下面的代码:from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import StaleElementReferenceException
import time

def login_fx(username,password):
    ......      # 此处是用登录bilbili的代码,最终返回一个已经登录的浏览器(B站首页)

def comment_fx():
    browser.get(F"ht请tps:/把/sp我ace.bil去ibili.co掉m/119/dyn!amic")    # 访问个人空间
    actions2 = ActionChains(browser)   # 重新实例化ActionChains对象
    time.sleep(1)
    browser.find_element_by_class_name("comment").click()    # 点击以展开评论区
    time.sleep(3)
    browser.find_element_by_class_name("ipt-txt").send_keys("123")   # 查找评论框


"""
username = str(input("用户名:"))
password = str(input("密码:"))
"""

login_fx(username,password)
comment_fx()

报错如下:
Traceback (most recent call last):
File "E:\002.py", line 55, in <module>
    comment_fx()
File "E:\002.py", line 41, in comment_fx
    browser.find_element_by_class_name("ipt-txt").send_keys("123")
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 564, in find_element_by_class_name
    return self.find_element(by=By.CLASS_NAME, value=name)
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
File "D:\Python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
File "D:\Python\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ipt-txt"}
(Session info: chrome=91.0.4472.114)

XPath表达式和class属性均无法使用,我该怎么办?

nahongyan1997 发表于 2021-8-8 16:01:29

browser.find_element_by_class_name("comment").click()    # 点击以展开评论区

改成

btn = browser.find_element_by_class_name("comment")

browser.execute_script("arguments.click()",btn)


就好了

DrWhiter 发表于 2021-8-9 15:04:41

向下方滚动也无法加载
页: [1]
查看完整版本: 关于selenium定位元素的问题