937135952 发表于 2022-12-19 14:19:29

关于selenium自动点击的问题

    date = "2022-12-19"
    driver.find_element(By.XPATH, '//span').click()   

如上代码想要实现如下的效果,应该怎么写
driver.find_element(By.XPATH, '//span').click()

isdkz 发表于 2022-12-19 14:46:50

    date = "2022-12-19"
    driver.find_element(By.XPATH, f'//span').click()   

937135952 发表于 2022-12-19 15:21:36

isdkz 发表于 2022-12-19 14:46


按照这个方法的话,会报错
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span"}

isdkz 发表于 2022-12-19 15:23:16

937135952 发表于 2022-12-19 15:21
按照这个方法的话,会报错
NoSuchElementException: no such element: Unable to locate element: {"met ...

因为没有一个 span 标签的内容是 2022-12-19,所以因为定位不到标签报错

你这个应该也是运行不了的:
driver.find_element(By.XPATH, '//span').click()

937135952 发表于 2022-12-19 15:23:27

isdkz 发表于 2022-12-19 14:46


def get_zhongxinjiantou():
   
    s = requests.Session()
   
    fb = webdriver.FirefoxProfile.DEFAULT_PREFERENCES
    # op = webdriver.FirefoxOptions()
    # op.set_preference({'user-data-dir':''})
    c = webdriver.ChromeOptions()
    c.add_argument('--user-data-dir=D:/AutomationProfile')
    # c.add_argument('--headless')
    # c.add_argument(f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36')
    driver = webdriver.Chrome()
   
    driver.get('https://www.cfc108.com/main/yfzx/rcbg/zaohui/index.shtml')
    time.sleep(3)
   
    date = "2022-12-19"
    driver.find_element(By.XPATH, f'//span').click()   
    #driver.find_element(By.XPATH, f'//span').click()
    #driver.find_element(By.XPATH, '//div[@id="mmain"]/ul/li/span').click()
    time.sleep(3)
    driver.find_element(By.XPATH, '//a').click()
    time.sleep(3)

isdkz 发表于 2022-12-19 15:30:02

937135952 发表于 2022-12-19 15:23


是我搞错了{:10_277:}

isdkz 发表于 2022-12-19 15:32:18

本帖最后由 isdkz 于 2022-12-19 15:35 编辑

    date = "2022-12-19"
    driver.find_element(By.XPATH, f'//span').click()      # 这里加多一个 !r,或者你把 {date!r} 换成 "{date}" 也行,是因为少了双引号出错,我把这个给漏了,!r可以让date以python表达式的方式代入(比如字符串带引号)

937135952 发表于 2022-12-20 09:54:06

isdkz 发表于 2022-12-19 15:32


date = "2022-12-19"
driver.find_element(By.XPATH, f'//div').click()
请问如果我想实现这样子的text()检索,应该怎么写呢

isdkz 发表于 2022-12-20 10:02:34

937135952 发表于 2022-12-20 09:54
请问如果我想实现这样子的text()检索,应该怎么写呢

date = "2022-12-19"
driver.find_element(By.XPATH, f'//div').click()          # {date!r}里面不要!r,!r会给字符串类型加上引号
页: [1]
查看完整版本: 关于selenium自动点击的问题