Python Selenium无法单击()按钮

时间:2018-05-15 15:52:19

标签: python selenium-webdriver

我试图从这里自动抓取链接:

https://thegoodpubguide.co.uk/pubs/?paged=1&order_by=category&search=pubs&pub_name=&postal_code=&region=london

一旦我有了第一页,我想点击底部的右边V形,以便移动到第二页,第三页,依此类推。刮掉两者之间的链接。

不幸的是,我尝试的任何内容都不允许我将chrome发送到下一页。

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    from datetime import datetime
    import csv
    from selenium.webdriver.common.action_chains import ActionChains

    #User login info
    pagenum = 1

    #Creates link to Chrome Driver and shortens this to 'browser'
    path_to_chromedriver = '/Users/abc/Downloads/chromedriver 2' # change path as needed
    driver = webdriver.Chrome(executable_path = path_to_chromedriver)

    #Navigates Chrome to the specified page
    url = 'https://thegoodpubguide.co.uk/pubs/?paged=1&order_by=category&search=pubs&pub_name=&postal_code=&region=london'


    #Clicks Login
    def findlinks(address):

        global pagenum

        list = []

        driver.get(address)
        #wait
        while pagenum <= 2:

            for i in range(20): # Scrapes available links
                xref = '//*[@id="search-results"]/div[1]/div[' + str(i+1) + ']/div/div/div[2]/div[1]/p/a'
                link = driver.find_element_by_xpath(xref).get_attribute('href')
                print(link)
                list.append(link)

            with open("links.csv", "a") as fp: # Saves list to file 
                wr = csv.writer(fp, dialect='excel')
                wr.writerow(list)

            print(pagenum)

            pagenum = pagenum + 1

            element = driver.find_element_by_xpath('//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a')
            element.click()


    findlinks(url)

阻止按钮的东西是我没看到的吗?

我的终端中打印的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a"}

2 个答案:

答案 0 :(得分:1)

试试这个:

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[class='next-page btn']"))  
element.click()

答案 1 :(得分:0)

编辑:

您为雪佛龙指定的xpath在页面之间是可变的,并且不完全正确。请注意li[8]li[9]以及//*[@id="search-results"]/div[2]/div/div/ul/li[6]/a/i

第1页:xpath为//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a/i

第2页:xpath为//*[@id="search-results"]/div[2]/div/div/ul/li[9]/a/i

第3页:xpath为li

您必须想出一些方法来确定要使用的xpath。这是一个提示:似乎//*[@id="search-results"]/div[2]/div/div/ul/下的最后time.sleep(...)指的是雪佛龙。

原始帖子:

在尝试查找并单击V形符号之前,您可能需要尝试等待页面加载。我通常只是在测试自动化脚本时执行Waits,但对于(可能)更复杂的功能,请尝试{{1}}。请参阅文档here