爬虫3_爬取翻页URL不变的网站

之前实现了对大学排数据爬取:爬虫2_2019年549所中国大学排名.

近期复现代码,发现原网站升级,在翻页时,发现URL不改变,修改代码,使用网页自动化工具selenium实现对该类网站数据获取。

python 复制代码
#-*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import bs4
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains  # 鼠标操作
from selenium.webdriver.common.by import By
import time

def get_info(soup, _type, element, param=None):
    if _type == "find":
        if param is not None:
            params = dict([param.split('=')])
            res = soup.find(element, **params)
        else:
            res = soup.find(element)
        if res is not None:
            res = res.string.replace(" ", "").replace("\n", "")
        else:
            res = "None"
    if _type == "find_all":
        if param is not None:
            params = dict([param.split('=')])
            res = soup.find_all(element, **params)
        else:
            res = soup.find_all(element)        
    return res


def fillUnivList(html):
    soup = BeautifulSoup(html, 'html.parser')
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):  # 如果为Tag类型
            td_list = tr.find_all('td')
            "排名"
            top = get_info(td_list[0], "find", "div", "class_=ranking")
            "logo"
            logo = td_list[1].find('img')["src"]
            "中文名/英文名"
            university_list = get_info(td_list[1], "find_all", "a")
            ch_name = university_list[0].string.replace("\n", "").replace("\t", "").strip(" ")
            en_name = university_list[1].string.replace("\n", "").strip(" ")
            "学校标签"
            tags = get_info(td_list[1], "find", "p")
            "学校地址"
            area = td_list[2].text.replace("\n", "").strip(" ")
            "学校行业"
            main = td_list[3].text.replace("\n", "").strip(" ")
            "综合分数"
            score = td_list[4].text.replace("\n", "").strip(" ")
            "办学层次"
            layer = td_list[5].text.replace("\n", "").strip(" ")
            print("{:<3}|{}|{:<80}|{}|{}|{}|{:<6}|{:<5}|{}".format(
                top, ch_name.ljust(14, "\u3000"),en_name, tags.ljust(12, "\u3000"), area.ljust(4, "\u3000"), 
                main.ljust(4, "\u3000"), score, layer, logo))


def action_run(driver, actions, info, by=By.ID, time_num=1):
    while 1:
        config_facesearch =  driver.find_element(by=by, value=info)
        if config_facesearch.is_displayed():
            actions.move_to_element(config_facesearch).click().perform()
            time.sleep(time_num) 
            break
        else:
            print("%s is not find, watting..." % (info))
            time.sleep(1)

if __name__ == "__main__":
    url = "https://www.shanghairanking.cn/rankings/bcur/2023"
    start = time.strftime("%H:%M:%S", time.localtime())
    driver = webdriver.Firefox()
    # driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(url)
    time.sleep(2)

    "鼠标操作"
    actions = ActionChains(driver)

    for i in range(20):
        html = driver.page_source
        fillUnivList(html)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")  # 滚动至底部
        action_run(driver, actions, info="li[title='下一页']", by=By.CSS_SELECTOR)
    
    end = time.strftime("%H:%M:%S", time.localtime())
    print("用时%s - %s" % (start, end))
    # 关闭浏览器
    driver.quit()
相关推荐
应用市场3 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑3 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
Dfreedom.3 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生3 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
叶子丶苏4 小时前
第八节_PySide6基本窗口控件_按钮类控件(QAbstractButton)
python·pyqt
百锦再5 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
Blossom.1186 小时前
把AI“刻”进玻璃:基于飞秒激光量子缺陷的随机数生成器与边缘安全实战
人工智能·python·单片机·深度学习·神经网络·安全·机器学习
Kratzdisteln6 小时前
【Python OOP Diary 1.1】题目二:简单计算器,改错与优化
python·面向对象编程
小白银子6 小时前
零基础从头教学Linux(Day 53)
linux·运维·python
skywalk81637 小时前
基于频域的数字盲水印blind-watermark
linux·开发语言·python