【问题标题】:Can't keep clicking on the next page button while parsing the links解析链接时无法继续单击下一页按钮
【发布时间】:2019-07-16 19:31:26
【问题描述】:

我已经在 python 中结合 selenium 编写了一个脚本来单击 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)

【问题讨论】:

  • 您是否遇到任何异常或浏览器冻结?你说的“然后卡住”是什么意思?
  • 这是错误(简洁)raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Other element would receive the click

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


【解决方案1】:

我打印出异常,它说元素不可点击。除了点击它,另一种方法是使用send_keys("\n") 来模拟链接点击。

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

我试过了,我可以导航到所有页面。

【讨论】:

  • 真棒@Bitto Bennichan !!!。为了清楚起见,您能否告诉我更多关于.send_keys("\n") 的信息。谢谢。
  • @MITHU 我们只是模拟使用键而不是鼠标的点击。这是一种 hack,但有时非常有用。
【解决方案2】:

如果你想抓取数据,不需要 Selenium。您可以使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-04
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多