python selenium点击按钮xpath错误

时间:2016-01-22 16:09:05

标签: python selenium web-scraping

我正在努力削减一个限量发行的房子。我不知道如何获得完整的便利设施清单,而不是点击"更多"。我使用selenium来模拟点击,但它似乎不起作用。

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

url = 'https://www.airbnb.com/rooms/4660676'
driver = webdriver.Firefox()
driver.get(url)
elem = driver.find_element_by_xpath('//a[@class="expandable-trigger-more"]')
actions.click(elem).perform()

2 个答案:

答案 0 :(得分:4)

XPath本身是正确的,但您尚未定义actions

from selenium.webdriver.common.action_chains import ActionChains

elem = driver.find_element_by_xpath('//a[@class="expandable-trigger-more"]')

actions = ActionChains(driver)
actions.click(elem).perform()

请注意,您只需使用WebElement click()方法:

elem = driver.find_element_by_xpath('//a[@class="expandable-trigger-more"]')
elem.click()

适合我。

如果您收到NoSuchElementException错误,则可能需要等待通过WebDriverWaitelement_to_be_clickable点击该链接。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//a[@class="expandable-trigger-more"]'))
)
element.click()

答案 1 :(得分:1)

下面提供了一种非常简单的方法来实现这一目标

onSubmit() {

    this.authService.Authenticate(this.model)
        .pipe(first())
        .subscribe(
        _data => {                
            this.router.navigate(['/admin/dashboard'])
        },
        error => {
            console.log('Authentication process failed')
            this.model.Error = error;
            this.authFailure = true;
        }
    );

}

    Authenticate(signIn: SignIn) {

    let authenticateUrl = this.configuration.Server + 'api/auth/Authenticate';
    const toSignIn = JSON.stringify(signIn);

    return this.http.post<SignIn>(authenticateUrl, toSignIn, { headers: this.headers })
        .pipe(
            map(result => {
            if (result && result.Token) { 
                // Store user details and the jwt token
                localStorage.setItem('accessToken', result.Token);
                localStorage.setItem('userName', result.Username);
                localStorage.setItem('name', result.Firstname + ' ' + result.Lastname);
                this.authCookie.writeAuthCookies(result);                    
            }
            return result;
        })
    );
}

canActivate(_next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    if (this.cookieAuth.readTokenOrCookie() === false) {

        // Redirect the request to signIn
        this.router.navigate(['/home/signin'], { queryParams: { return: state.url } });
        return false;
    }

    return true;        
}

它对我有用,希望也对您有用。