解析链接时无法继续单击下一页按钮

时间:2019-02-22 16:44:21

标签: python python-3.x selenium selenium-webdriver web-scraping

我已经用python与硒结合编写了一个脚本,单击search按钮以填充结果,然后从其着陆页解析来自类ya_result-item的不同链接,然后继续单击下一页按钮,同时解析其他页面的链接,直到没有更多按钮可以单击为止。

但是,我的脚本只能解析第一页上的链接,然后单击下一页按钮一次,但是卡住了。

website link

如何在解析链接时使脚本不断单击下一页按钮?

这是我的尝试:

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

url = "https://www.yogaalliance.org/Directory?Type=School"

def get_page_content(driver,link):
    driver.get(link)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.ya_directory-search-button"))).click()
    while True:
        for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[id^='ya_result-item'] a[href^='/SchoolPublicProfile']"))):
            print(item.get_attribute("href"))

        try:
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "a[title*='next page']"))).click()
            wait.until(EC.staleness_of(item))
        except Exception:break

if __name__ == '__main__':
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver,10)
    get_page_content(driver,url)

2 个答案:

答案 0 :(得分:2)

我打印出异常,它说元素不可点击。除了点击以外,还可以使用send_keys("\n")模拟链接点击。

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "a[title*='next page']"))).send_keys("\n")

我尝试了一下,并且能够导航到所有页面。

答案 1 :(得分:2)

如果您要抓取数据,则无需硒。您可以使用requests包以json格式更快地获取所有信息。

下面的代码收集所有学校的详细信息,作为result中的地图列表:

import requests

data = {
    'take': '10',
    'skip': '0',
    'page': '1',
    'pageSize': '10',
    'pageIndex': '0'
}
url = 'https://www.yogaalliance.org/DesktopModules/YAServices/API/SchoolDirectory/SearchSchools'
response = requests.post(url, data=data)

result = response.json()["Result"]
totalCount = response.json()["TotalCount"]
totalCount = int(totalCount / 10)

for i in range(1, totalCount):
    data['skip'] = int(data['skip']) + 10
    data['page'] = i + 1
    data['pageIndex'] = i
    response = requests.post(url, data=data)
    result.extend(response.json()["Result"])

print(result)