Python-Selenium下一页

时间:2018-09-20 09:49:34

标签: python selenium selenium-webdriver web-scraping webdriver

我正在尝试制作一个抓取应用程序以抓取Hants.gov.uk,现在我正在处理它,只是单击页面而不是抓取。当它到达页面1的最后一行时,它刚刚停止,所以我要做的是单击按钮“下一页”,但是首先必须返回到原始URL。它单击了第2页,但是在抓取了第2页之后,它没有转到第3页,而是仅重新启动了第2页。

有人可以帮我解决此问题吗?

代码:

import time
import config # Don't worry about this. This is an external file to make a DB
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://planning.hants.gov.uk/SearchResults.aspx?RecentDecisions=True"

driver = webdriver.Chrome(executable_path=r"C:\Users\Goten\Desktop\chromedriver.exe")
driver.get(url)

driver.find_element_by_id("mainContentPlaceHolder_btnAccept").click()

def start():
    elements = driver.find_elements_by_css_selector(".searchResult a")
    links = [link.get_attribute("href") for link in elements]

    result = []
    for link in links:
        if link not in result:
            result.append(link)
        else:
            driver.get(link)
            goUrl = urllib.request.urlopen(link)
            soup = BeautifulSoup(goUrl.read(), "html.parser")
            #table = soup.find_element_by_id("table", {"class": "applicationDetails"})
            for i in range(20):
                pass # Don't worry about all this commented code, it isn't relevant right now
                #table = soup.find_element_by_id("table", {"class": "applicationDetails"})
                #print(table.text)
            #   div = soup.select("div.applicationDetails")
            #   getDiv = div[i].split(":")[1].get_text()
            #   log = open("log.txt", "a")
            #   log.write(getDiv + "\n")
            #log.write("\n")

start()
driver.get(url)

for i in range(5):
    driver.find_element_by_id("ctl00_mainContentPlaceHolder_lvResults_bottomPager_ctl02_NextButton").click()
    url = driver.current_url
    start()
    driver.get(url)
driver.close()

3 个答案:

答案 0 :(得分:1)

尝试一下:

import time
# import config # Don't worry about this. This is an external file to make a DB
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://planning.hants.gov.uk/SearchResults.aspx?RecentDecisions=True"

driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_id("mainContentPlaceHolder_btnAccept").click()

result = []


def start():
    elements = driver.find_elements_by_css_selector(".searchResult a")
    links = [link.get_attribute("href") for link in elements]
    result.extend(links)

def start2():
    for link in result:
        # if link not in result:
        #     result.append(link)
        # else:
            driver.get(link)
            goUrl = urllib.request.urlopen(link)
            soup = BeautifulSoup(goUrl.read(), "html.parser")
            #table = soup.find_element_by_id("table", {"class": "applicationDetails"})
            for i in range(20):
                pass # Don't worry about all this commented code, it isn't relevant right now
                #table = soup.find_element_by_id("table", {"class": "applicationDetails"})
                #print(table.text)
            #   div = soup.select("div.applicationDetails")
            #   getDiv = div[i].split(":")[1].get_text()
            #   log = open("log.txt", "a")
            #   log.write(getDiv + "\n")
            #log.write("\n")


while True:
    start()
    element = driver.find_element_by_class_name('rdpPageNext')
    try:
        check = element.get_attribute('onclick')
        if check != "return false;":
            element.click()
        else:
            break

    except:
        break

print(result)
start2()
driver.get(url)

答案 1 :(得分:1)

根据网址this.criteriaSelectedMeasures$.subscribe(list => { this.store.dispatch(new AddMeasureDefinitionsAction(list.filter(m => m.isSelected))); <-- here isSelected is always false }); 单击所有页面,您可以使用以下解决方案:

  • 代码块:

    https://planning.hants.gov.uk/SearchResults.aspx?RecentDecisions=True
  • 控制台输出:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    options = Options()
    options.add_argument("start-maximized")
    options.add_argument("disable-infobars")
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('https://planning.hants.gov.uk/SearchResults.aspx?RecentDecisions=True')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "mainContentPlaceHolder_btnAccept"))).click()
    numLinks = len(WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div#ctl00_mainContentPlaceHolder_lvResults_topPager div.rdpWrap.rdpNumPart>a"))))
    print(numLinks)
    for i in range(numLinks):
        print("Perform your scrapping here on page {}".format(str(i+1)))
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='ctl00_mainContentPlaceHolder_lvResults_topPager']//div[@class='rdpWrap rdpNumPart']//a[@class='rdpCurrentPage']/span//following::span[1]"))).click()
    driver.quit()
    

答案 2 :(得分:0)

嗨,@ Feitan Portor,您已经完美地编写了代码,将您重定向回首页的唯一原因是,因为您在最后一个for循环中给了url = driver.current_url,其中URL保持静态,只有引发下一次点击事件的Java脚本,因此只需删除url = driver.current_urldriver.get(url)

你很好,我已经测试了我的自我 还要获取刮板所在的当前页面,只需将这部分添加到for循环中,这样您就可以知道刮板的位置:

ss = driver.find_element_by_class_name('rdpCurrentPage').text
    print(ss)

希望这可以解决您的困惑