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

news/2024/7/19 9:44:33 标签: python, 爬虫

之前实现了对大学排数据爬取:爬虫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()

代码运行结果


http://www.niftyadmin.cn/n/5430146.html

相关文章

go的slice学习

并发访问slice 线上出现一粒多协程并发append全局slice的情况&#xff0c;导致内存不断翻倍&#xff0c;因此对slice的使用需要重新考虑。 并发读写的情况下&#xff0c; 可以利用锁、channel等避免竞态 问题 func TestDemo32(t *testing.T) {var wg sync.WaitGroupvar n 1…

Go微服务实战——服务的配置获取(nacos做配置中心)

nacos做配置中心 demo仓库 docker安装nacos docker pull nacos/nacos-server 使用docker每次需要sudo可以执行如下命令 sudo groupadd docker #添加用户组 sudo gpasswd -a username docker #将当前用户添加至用户组-d就是删除该组中的用户 newgrp docker…

【刷题训练】LeetCode125. 验证回文串

验证回文串 题目要求 示例 1&#xff1a; 输入: s “A man, a plan, a canal: Panama” 输出&#xff1a;true 解释&#xff1a;“amanaplanacanalpanama” 是回文串。 示例 2&#xff1a; 输入&#xff1a;s “race a car” 输出&#xff1a;false 解释&#xff1a;“rac…

无人机自动返航算法实现与优化

一、引言 随着无人机技术的快速发展&#xff0c;其在航拍、农业、救援等领域的应用越来越广泛。在这些应用中&#xff0c;无人机的自动返航功能显得尤为重要。一旦无人机失去控制或与遥控器失去连接&#xff0c;自动返航算法能够确保无人机安全返回起飞点&#xff0c;避免损失和…

蓝桥杯(1):python排序

1 基础 1.1 输出 1.1.1 去掉输出的空格 print("Hello","World",123,sep"") print("hello",world,123,sep) print(hello,world,123) #输出结果 #HelloWorld123 #helloworld123 #hello world 123 1.1.2 以不同的方式结尾 print(&quo…

docker部署mysql5

1. 进入面板 2. 新建挂载文件夹 新建三个文件夹: mkdir -p /docker/mysql5/config && mkdir -p /docker/mysql5/data && mkdir -p /docker/mysql5/logsconfig&#xff1a;存放mysql配置data&#xff1a;存放mysql数据logs&#xff1a;存放mysql记录日志 3.…

python的程序调试方法有哪些?

调试python程序&#xff0c;让程序在不同的节点把运行结果消失出来&#xff0c;看与程序设计者预想的结果是否一致&#xff0c;从而确定程序设计中存在的问题&#xff0c;最简单的方法是在程序的不同节点使用print语句打印出变量的值。除此之外&#xff0c;使用程序运行日志、使…

【进阶五】Python实现SDVRP(需求拆分)常见求解算法——蚁群算法(ACO)

基于python语言&#xff0c;采用经典遗传算法&#xff08;ACO&#xff09;对 需求拆分车辆路径规划问题&#xff08;SDVRP&#xff09; 进行求解。 目录 往期优质资源1. 适用场景2. 代码调整3. 求解结果4. 代码片段参考 往期优质资源 经过一年多的创作&#xff0c;目前已经成熟…