Python pygame实现中国象棋单机版源码

Python中国象棋单机版

鼠标点击操作;两天制作,较为粗糙,很多效果还未实现。

# -*- coding: utf-8 -*-
"""
Created on Sun Jun 13 15:41:56 2021

@author: Administrator
"""

import pygame
from pygame.locals import *
import sys
import math

pygame.init()
screen=pygame.display.set_mode((450,550))
pygame.display.set_caption('中国象棋')

img_board=pygame.image.load('F:/images/中国象棋/board.png')
img_redSoldier=pygame.image.load('F:/images/中国象棋/chess_redSoldier.png')
img_redCannon=pygame.image.load('F:/images/中国象棋/chess_redCannon.png')
img_redCar=pygame.image.load('F:/images/中国象棋/chess_redCar.png')
img_redHorse=pygame.image.load('F:/images/中国象棋/chess_redHorse.png')
img_redElephant=pygame.image.load('F:/images/中国象棋/chess_redElephant.png')
img_redAttendant=pygame.image.load('F:/images/中国象棋/chess_redAttendant.png')
img_chief=pygame.image.load('F:/images/中国象棋/chess_chief.png')
img_blackSoldier=pygame.image.load('F:/images/中国象棋/chess_blackSoldier.png')
img_blackCannon=pygame.image.load('F:/images/中国象棋/chess_blackCannon.png')
img_blackCar=pygame.image.load('F:/images/中国象棋/chess_blackCar.png')
img_blackHorse=pygame.image.load('F:/images/中国象棋/chess_blackHorse.png')
img_blackElephant=pygame.image.load('F:/images/中国象棋/chess_blackElephant.png')
img_blackAttendant=pygame.image.load('F:/images/中国象棋/chess_blackAttendant.png')
img_general=pygame.image.load('F:/images/中国象棋/chess_general.png')

screen.blit(img_board,(0,0))
pygame.display.update()

red_chess=[[0,6],[2,6],[4,6],[6,6],[8,6],[1,7],[7,7],[0,9],[1,9],[2,9],[3,9],[4,9],[5,9],[6,9],[7,9],[8,9]]
black_chess=[[0,3],[2,3],[4,3],[6,3],[8,3],[1,2],[7,2],[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0]]

#画棋子
def draw_chess():
    for i in range(len(red_chess)):
        if 0<=i<=4:
            screen.blit(img_redSoldier,(red_chess[i][0]*50,red_chess[i][1]*50))
        elif 5<=i<=6:
            screen.blit(img_redCannon,(red_chess[i][0]*50,red_chess[i][1]*50))
        elif i==7 or i==15:
            screen.blit(img_redCar,(red_chess[i][0]*50,red_chess[i][1]*50))
        elif i==8 or i==14:
            screen.blit(img_redHorse,(red_chess[i][0]*50,red_chess[i][1]*50))
        elif i==9 or i==13:
            screen.blit(img_redElephant,(red_chess[i][0]*50,red_chess[i][1]*50))
        elif i==10  or i==12:
            screen.blit(img_redAttendant,(red_chess[i][0]*50,red_chess[i][1]*50))
        else:
            screen.blit(img_chief,(red_chess[i][0]*50,red_chess[i][1]*50))
    for i in range(len(black_chess)):
        if 0<=i<=4:
            screen.blit(img_blackSoldier,(black_chess[i][0]*50,black_chess[i][1]*50))
        elif 5<=i<=6:
            screen.blit(img_blackCannon,(black_chess[i][0]*50,black_chess[i][1]*50))
        elif i==7 or i==15:
            screen.blit(img_blackCar,(black_chess[i][0]*50,black_chess[i][1]*50))
        elif i==8 or i==14:
            screen.blit(img_blackHorse,(black_chess[i][0]*50,black_chess[i][1]*50))
        elif i==9 or i==13:
            screen.blit(img_blackElephant,(black_chess[i][0]*50,black_chess[i][1]*50))
        elif i==10  or i==12:
            screen.blit(img_blackAttendant,(black_chess[i][0]*50,black_chess[i][1]*50))
        else:
            screen.blit(img_general,(black_chess[i][0]*50,black_chess[i][1]*50))
    pygame.display.update()

#返回1表示正常移动,返回2表示有子被吃,返回0表示拒绝移动
#兵移动规则,红兵chess1为red_chess,chess2为black_chess
def soldier_rule(chess1,chess2,current_pos,next_pos):
    if chess1==red_chess:
        pos,index=[5,6],1
    elif chess1==black_chess:
        pos,index=[3,4],-1
    if current_pos[1] in pos:
        if current_pos[0]==next_pos[0] and current_pos[1]==next_pos[1]+index and next_pos not in chess1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            current_pos=next_pos
            return [current_pos,1]
    else:
        if current_pos[0]==next_pos[0] and current_pos[1]==next_pos[1]+index and next_pos not in chess1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            current_pos=next_pos
            return [current_pos,1]
        elif current_pos[1]==next_pos[1] and current_pos[0]+1==next_pos[0] and next_pos not in chess1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            current_pos=next_pos
            return [current_pos,1]
        elif current_pos[1]==next_pos[1] and current_pos[0]-1==next_pos[0] and next_pos not in chess1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            current_pos=next_pos
            return [current_pos,1]

#车移动规则,红车前两个参数为red_chess、black_chess,黑车前两个参数为black_chess、red_chess
def car_rule(chess1,chess2,current_pos,next_pos):
    if next_pos not in chess1 and current_pos[0]==next_pos[0]:
        a,b=current_pos,next_pos
        if a[1]>b[1]:
            a,b=b,a
        for i in range(a[1]+1,b[1]):
            if [a[0],i] in black_chess+red_chess:
                return 0
        for i in range(len(chess2)):
            if chess2[i]==next_pos:
                chess2[i]=[-1,-1]
                current_pos=next_pos
                return [current_pos,2]
        current_pos=next_pos
        return [current_pos,1]
    elif next_pos not in chess1 and current_pos[1]==next_pos[1]:
        a,b=current_pos,next_pos
        if a[0]>b[0]:
            a,b=b,a
        for i in range(a[0]+1,b[0]):
            if [i,a[1]] in black_chess+red_chess:
                return 0
        for i in range(len(chess2)):
            if chess2[i]==next_pos:
                chess2[i]=[-1,-1]
                current_pos=next_pos
                return [current_pos,2]
        current_pos=next_pos
        return [current_pos,1]

#炮移动规则
def cannon_rule(chess1,chess2,current_pos,next_pos):
    if next_pos not in chess1 and current_pos[0]==next_pos[0]:
        num=0
        a,b=current_pos,next_pos
        if a[1]>b[1]:
            a,b=b,a
        for i in range(a[1]+1,b[1]):
            if [a[0],i] in black_chess+red_chess:
                num+=1
        if num==1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            return 0
        elif num==0:
            current_pos=next_pos
            return [current_pos,1]
        else:
            return 0
    elif next_pos not in chess1 and current_pos[1]==next_pos[1]:
        num=0
        a,b=current_pos,next_pos
        if a[0]>b[0]:
            a,b=b,a
        for i in range(a[0]+1,b[0]):
            if [i,a[1]] in black_chess+red_chess:
                num+=1
        if num==1:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
            return 0
        elif num==0:
            current_pos=next_pos
            return [current_pos,1]
        else:
            return 0

#马移动规则,红马chess为black_chess
def horse_rule(chess,current_pos,next_pos):
    index=[[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1]]
    leg=[[1,0],[0,-1],[0,-1],[-1,0],[-1,0],[0,1],[0,1],[1,0]]
    if next_pos not in red_chess+black_chess:
        for i in range(len(index)):
            if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]:
                if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess:
                    current_pos=next_pos
                    return [current_pos,1]
    elif next_pos in chess:
        for i in range(len(index)):
            if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]:
                if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess:
                    for i in range(len(chess)):
                        if chess[i]==next_pos:
                            chess[i]=[-1,-1]
                            current_pos=next_pos
                            return [current_pos,2]

#象移动规则,红相chess为black_chess
def elephant_rule(chess,current_pos,next_pos):
    index=[[2,-2],[-2,-2],[-2,2],[2,2]]
    leg=[[1,-1],[-1,-1],[-1,1],[1,1]]
    if chess==black_chess:
        pos=[5,7,9]
    elif chess==red_chess:
        pos=[0,2,4]
    if next_pos not in red_chess+black_chess and next_pos[1] in pos:
        for i in range(len(index)):
            if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]:
                if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess:
                    current_pos=next_pos
                    return [current_pos,1]
    elif next_pos in chess and next_pos[1] in pos:
        for i in range(len(index)):
            if current_pos[0]+index[i][0]==next_pos[0] and current_pos[1]+index[i][1]==next_pos[1]:
                if [current_pos[0]+leg[i][0],current_pos[1]+leg[i][1]] not in black_chess+red_chess:
                    for i in range(len(chess)):
                        if chess[i]==next_pos:
                            chess[i]=[-1,-1]
                            current_pos=next_pos
                            return [current_pos,2]

#士移动规则
def attendant_rule(chess1,chess2,current_pos,next_pos):
    if chess1==red_chess:
        pos1=[[3,9],[3,7],[5,7],[5,9]]
        pos2=[4,8]
    elif chess1==black_chess:
        pos1=[[3,0],[3,2],[5,2],[5,0]]
        pos2=[4,1]
    if current_pos in pos1 and next_pos==pos2 and next_pos not in chess1:
        if next_pos not in chess2:
            current_pos=next_pos
            return [current_pos,1]
        else:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]
    elif current_pos==pos2 and next_pos in pos1 and next_pos not in chess1:
        if next_pos not in chess2:
            current_pos=next_pos
            return [current_pos,1]
        else:
            for i in range(len(chess2)):
                if chess2[i]==next_pos:
                    chess2[i]=[-1,-1]
                    current_pos=next_pos
                    return [current_pos,2]

#将帅移动规则
def boss_rule(chess1,chess2,current_pos,next_pos,j_pos):
    if chess1==red_chess:
        pos=[7,8,9]
    elif chess1==black_chess:
        pos=[0,1,2]
    flag=0
    if next_pos not in chess1:
        if next_pos[0]==j_pos[0]:
            for i in range(j_pos[1]+1,next_pos[1]):
                if [j_pos[0],j_pos[1]+i] in black_chess+red_chess:
                    flag=1
                    break
            if flag==0:
                return 0
    if next_pos not in chess1 and 3<=next_pos[0]<=5 and next_pos[1] in pos:
        if next_pos not in chess2:
            if current_pos[0]==next_pos[0]:
                if current_pos[1]+1==next_pos[1] or current_pos[1]-1==next_pos[1]:
                    current_pos=next_pos
                    return [current_pos,1]
            elif current_pos[1]==next_pos[1]:
                if current_pos[0]+1==next_pos[0] or current_pos[0]-1==next_pos[0]:
                    current_pos=next_pos
                    return [current_pos,1]
        else:
            if current_pos[0]==next_pos[0]:
                if current_pos[1]+1==next_pos[1] or current_pos[1]-1==next_pos[1]:
                    for i in range(len(chess2)):
                        if chess2[i]==next_pos:
                            chess2[i]=[-1,-1]
                            current_pos=next_pos
                            return [current_pos,2]
            elif current_pos[1]==next_pos[1]:
                if current_pos[0]+1==next_pos[0] or current_pos[0]-1==next_pos[0]:
                    for i in range(len(chess2)):
                        if chess2[i]==next_pos:
                            chess2[i]=[-1,-1]
                            current_pos=next_pos
                            return [current_pos,2]

#棋子移动
def move(chess1,chess2,next_pos):
    x=0
    if i in range(5):   #兵
        x=soldier_rule(chess1,chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    elif i==5 or i==6:  #炮
        x=cannon_rule(chess1,chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    elif i==7 or i==15: #車
        x=car_rule(chess1,chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    elif i==8 or i==14: #馬
        x=horse_rule(chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    elif i==9 or i==13: #相
        x=elephant_rule(chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    elif i==10 or i==12:    #仕
        x=attendant_rule(chess1,chess2,chess1[i],next_pos)
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    else:   #帥
        x=boss_rule(chess1,chess2,chess1[i],next_pos,chess2[11])
        if x!=None and x!=0:
            chess1[i]=x[0]
            print(chess1[i])
            screen.blit(img_board,(0,0))
            draw_chess()
    return x

white=(255,255,255)
black=(0,0,0)
def draw_text(text,x,y,size):
    pygame.font.init()
    fontObj=pygame.font.SysFont('SimHei',size )
    textSurfaceObj=fontObj.render(text, True, white,black)
    textRectObj=textSurfaceObj.get_rect()
    textRectObj.center=(x,y)
    screen.blit(textSurfaceObj, textRectObj)
    pygame.display.update()

#判断游戏是否结束
def game_over():
    if red_chess[11]==[-1,-1]:
        draw_text('黑方胜利',225,525,15)
        return 1
    elif black_chess[11]==[-1,-1]:
        draw_text('红方胜利',225,525,15)
        return 1

if __name__=='__main__':
    all_pos,progress=[],[]
    for i in range(10):
        for j in range(9):
            all_pos.append([j,i])
    draw_text('红方先走',225,525,15)
    chess_kind=0
    while True:
        draw_chess()
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
            elif event.type==MOUSEBUTTONDOWN:
                pos=pygame.mouse.get_pos()
                print(pos)
                if chess_kind==0:
                    chess1,chess2=red_chess,black_chess
                elif chess_kind==1:
                    chess1,chess2=black_chess,red_chess
                for i in range(len(chess1)):
                    if chess1[i][0]*50<pos[0]<(chess1[i][0]+1)*50 and chess1[i][1]*50<pos[1]<(chess1[i][1]+1)*50:
                        flag=False
                        while True:
                            for event in pygame.event.get():
                                if event.type==MOUSEBUTTONDOWN:
                                    pos=pygame.mouse.get_pos()
                                    next_pos=[pos[0]//50,pos[1]//50]
                                    flag=True
                                    break
                            if flag==True:
                                break
                        progress.append(move(chess1,chess2,next_pos))
                        if progress[-1]!=None and progress[-1]!=0:
                            if chess_kind==0:
                                chess_kind=1
                            elif chess_kind==1:
                                chess_kind=0
                        if chess_kind==1:
                            draw_text('轮到黑方',225,525,15)
                        elif chess_kind==0:
                            draw_text('轮到红方',225,525,15)
                        if game_over()==1:
                            while True:
                                for event in pygame.event.get():
                                    if event.type==QUIT:
                                        pygame.quit()
                                        sys.exit()
                        break

棋盘图片:

棋子图片:














运行效果:

到此这篇关于Python pygame实现中国象棋单机版源码的文章就介绍到这了,更多相关pygame实现中国象棋内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python图形工具turtle绘制国际象棋棋盘

    本文实例为大家分享了python图形工具turtle绘制国际象棋棋盘的具体代码,供大家参考,具体内容如下 #编写程序绘制一个国际象棋的棋盘 import turtle turtle.speed(30) turtle.penup() off = True for y in range(-40, 30 + 1, 10): for x in range(-40, 30 + 1, 10): if off: turtle.goto(x, y) turtle.pendown() turtle.begin_f

  • python输出国际象棋棋盘的实例分享

    国际象棋是当今国际上最流行的智力体育运动项目.青年人下棋可以锻炼思维.增强记忆力和培养坚强的意志:中年人下棋可以享受美学:老年下棋可以很好的休息娱乐.国际象棋游戏有自己的规则,需要两个人将棋子落在棋盘上. 棋子落在棋盘上事件,在计算机看来,是一段程序,而这些程序又由一系列的指令组成.关心编程语言的使用趋势的人都知道,最近几年,国内最火的两种语言非 Python 与 Go 莫属,今天,我们就在计算机上用python开启一段输出国际象棋棋盘的编程之旅. 程序分析:用i控制行,j来控制列,根据i+j的

  • python使用turtle绘制国际象棋棋盘

    本文实例为大家分享了python使用turtle画国际象棋棋盘的具体代码,供大家参考,具体内容如下 使用的方法是每一个小格每一个小格的画 import turtle for i in range(8): #一共有八列 for j in range(8):#每一行有八个格 turtle.forward(37.5) if j % 2 == 0:#判断是否为第奇数个格(是否画黑色格) if i % 2 ==0:#判断是否为奇数行(调整画黑色正方形时小海龟的转向) turtle.begin_fill()

  • Python turtle绘画象棋棋盘

    通过使用turtle绘画象棋棋盘,供大家参考,具体内容如下 # 绘制象棋棋盘 import turtle t = turtle.Pen() t.width(2) # 设置画笔粗细 t.speed(1) # 设置画笔移动速度 # 画竖线 t.penup() t.goto(-400, -400) for i in range(9): t.pendown() if i != 0 and i != 8: t.goto(-400+i*100, 0) t.penup() t.goto(-400+i*100,

  • 用Python编写一个国际象棋AI程序

    最近我用Python做了一个国际象棋程序并把代码发布在Github上了.这个代码不到1000行,大概20%用来实现AI.在这篇文章中我会介绍这个AI如何工作,每一个部分做什么,它为什么能那样工作起来.你可以直接通读本文,或者去下载代码,边读边看代码.虽然去看看其他文件中有什么AI依赖的类也可能有帮助,但是AI部分全都在AI.py文件中. AI 部分总述 AI在做出决策前经过三个不同的步骤.首先,他找到所有规则允许的棋步(通常在开局时会有20-30种,随后会降低到几种).其次,它生成一个棋步树用来

  • Python pygame实现中国象棋单机版源码

    Python中国象棋单机版 鼠标点击操作:两天制作,较为粗糙,很多效果还未实现. # -*- coding: utf-8 -*- """ Created on Sun Jun 13 15:41:56 2021 @author: Administrator """ import pygame from pygame.locals import * import sys import math pygame.init() screen=pygame.

  • Android实现中国象棋附源码下载

    象棋,很多人多接触过,学者写了一个,大神可以指点一下~直接上代码: 贴出主要代码,想要Demo的点击下载:中国象棋Demo package wyf.ytl; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; impor

  • python 爬取疫情数据的源码

    疫情数据 程序源码 // An highlighted block import requests import json class epidemic_data(): def __init__(self, province): self.url = url self.header = header self.text = {} self.province = province # self.r=None def down_page(self): r = requests.get(url=url

  • Python实现人机中国象棋游戏

    目录 导语 1.游戏规则&基本玩法 1.1 基本玩法 1.2 行棋规则 2.素材文件 3.主要代码 3.1 Chinachess.py 为主文件 3.2 Constants.py 数据常量 3.3 Pieces.py 棋子类,走法 3.4 Computer.py 电脑走法计算 3.5 Button.py按钮定义 4.游戏效果 总结 导语 哈喽!哈喽!我是木木子!今日游戏更新——中国象棋上线啦! 中国象棋是一种古老的棋类游戏,大约有两千年的历史. 是中华文明非物质文化经典产物,艺术价值泛属于整个人

  • 微信跳一跳python辅助软件思路及图像识别源码解析

    本文将梳理github上最火的wechat_jump_game的实现思路,并解析其图像处理部分源码 首先废话少说先看效果 核心思想 获取棋子到下一个方块的中心点的距离 计算触摸屏幕的时间 点击屏幕 重要方法 计算棋子到下一个方块中心点的距离 使用 adb shell screencap -p 命令获取手机当前屏幕画面 再通过图像上的信息找出棋子的坐标和下一个方块中心点的坐标 然后通过两点间距离公式计算出距离 计算触摸屏幕的时间 T=A * S 其中S为上步算出的像素距离,T为按压时间(ms),A

  • Python日志打印里logging.getLogger源码分析详解

    实践环境 WIN 10 Python 3.6.5 函数说明 logging.getLogger(name=None) getLogger函数位于logging/__init__.py脚本 源码分析 _loggerClass = Logger # ...略 root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) # ...略 def getLogger(name=None): "&quo

  • python 制作网站筛选工具(附源码)

    一.思路 1.整体思路 2.代码思路 思路很简单,就是用python发送请求,提取响应体中的状态码加以判断,最后保存到本地txt文本中,以实现网站信息的筛选. 二.撰写代码 import time import requests import urllib3 from concurrent.futures import ThreadPoolExecutor #取源文件中的网址并且去重 def get_url(old_file): with open(old_file,'r',encoding='

  • Python制作动态字符画的源码

    字符画,一种由字母.标点.汉字或其他字符组成的图画.简单的字符画是利用字符的形状代替图画的线条来构成简单的人物.事物等形象,它一般由人工制作而成:复杂的字符画通常利用占用不同数量像素的字符代替图画上不同明暗的点,它一般由程序制作而成.字符画是互联网时代的产物,通常应用于即时聊天中. 首先,也是最重要的,先放源码 from PIL import Image as im from tkinter import * import cv2 # 随便打 codeLib = '''*.1''' count

  • Python万物皆对象理解及源码学习

    目录 万物皆对象 1 类型对象和实例对象 2 类型.对象体系 2.1 元类型type 2.2 自定义类型 2.3 自定义类型子类 2.4 type和object的关系 3 可变对象与不可变对象 4 变长对象和定长对象 5 补充 万物皆对象 这篇博客的内容主要是针对Python中万物皆对象的理解,对Python的类型.对象体系做一个整体的梳理. 在Python中,一切皆为对象,一个整数是一个对象,一个字符串也是一个对象,基本类型(如int)也是对象.Python不再区别对待基本类型和对象,所有的基

  • Python无法用requests获取网页源码的解决方法

    最近在抓取http://skell.sketchengine.eu网页时,发现用requests无法获得网页的全部内容,所以我就用selenium先模拟浏览器打开网页,再获取网页的源代码,通过BeautifulSoup解析后拿到网页中的例句,为了能让循环持续进行,我们在循环体中加了refresh(),这样当浏览器得到新网址时通过刷新再更新网页内容,注意为了更好地获取网页内容,设定刷新后停留2秒,这样可以降低抓不到网页内容的机率.为了减少被封的可能,我们还加入了Chrome,请看以下代码: fro

随机推荐