def test_has_weapon(self):
     my_weapon = Weapon("axe", 30, 0.5)
     my_entity = Entity("Furious", 100)
     my_entity.equip_weapon(my_weapon)
     self.assertTrue(my_entity.has_weapon())
     my_entity = Entity("Furious", 100)
     self.assertFalse(my_entity.has_weapon())
示例#2
0
    def extract_evaluation_entities(self):
        print 'In extract evaluating entities'
        for dependency in self.m_dependencies:
            if dependency[0] == 'nsubj':
                self.m_has_a_nsubj = True
                self.m_nsubj = dependency[2]
                self.m_evaluating_subject = Entity('nsubj', self.m_nsubj)
            elif dependency[0] == 'dobj':
                # extract parts of speech of the relation dep and gov
                # if none of them is noun. apply some logic to find the evaluating object
                print self.m_words_pos
                temp_dobj = dependency[2]
                temp_dobj_pos = self.m_words_pos[temp_dobj]
                if temp_dobj_pos != None and temp_dobj_pos in PublicKeys.NOUN_POS:
                    self.m_has_a_dobj = True
                    self.m_dobj = dependency[2]
                    self.m_evaluating_object = Entity('dobj', self.m_dobj)
                else:
                    print 'Couldn\'t find a dobj noun'
                    max = 0
                    matching_noun = None
                    for noun in self.m_all_noun_lemmas:
                        for qes in self.m_question.get_quantified_entities(
                        ).values():
                            for qe in qes:
                                wup_similarity = self.word_similarity(
                                    noun,
                                    Sentence.LEMMATIZER_MODULE.lemmatize(
                                        qe.get_name()))
                                if max < wup_similarity:
                                    max = wup_similarity
                                    matching_noun = qe

                    self.m_evaluating_object = Entity('dobj',
                                                      matching_noun.get_name())
示例#3
0
    def getGroups(self):
        groupList = []
        groupsite = 'http://umu.sibadi.org/Dek/Default.aspx?mode=group'

        response = requests.get(groupsite)
        soup = BS(response.content, 'html.parser')

        groups = soup.findAll('tr', {'class': 'TblText'})

        for group in groups:
            group = group.find('a')
            group = group.get('href')
            groupId = group.split('id=')[1]

            url = 'http://umu.sibadi.org/Rasp/Rasp.aspx?group={}&sem=2'.format(
                groupId)
            name = groupId
            entity = Entity(name, url, 'group', None)
            groupList.append(entity)

        groups = soup.findAll('tr', {'class': 'TblhiText'})

        for group in groups:
            group = group.find('a')
            group = group.get('href')
            groupId = group.split('id=')[1]

            url = 'http://umu.sibadi.org/Rasp/Rasp.aspx?group={}&sem=2'.format(
                groupId)
            name = groupId
            entity = Entity(name, url, 'group', None)
            groupList.append(entity)

        return groupList
示例#4
0
  def __init__(self,index,sentence):
    self.logger = LoggerFactory(self).getLogger()
    if(sentence == ""): raise ValueError(f"Sentence is an empty string")

    self.index = index
    self.sentence = sentence
    self.type = Sentence.TYPE_STATEMENT
    self.tense = Sentence.TENSE_OTHERS
    self.structure = None
    self.verb = None
    self.ARG0 = []
    self.ARG1 = []
    self.ARG2 = []
    self.ARG3 = []
    self.ARG4 = []
    self.entity = Entity()
    self.actor = Entity()

    self.__parsePOS()
    # With POS, we can determine if the sentence is a query
    self.__checkType()
    self.__extractVerb()
    self.__checkTense()
    self.__parseSRL()
    self.__setSRLArgument()
    self.__setStructure()
示例#5
0
 def getEntities(self, ids):
     self.formatz['id'] = ','.join(map(str, ids))
     tmp = []
     try:
         url = self.url.format(**self.formatz)
         data = fetchUrl(url)
         ens = json.loads(data)['data']
     except:
         #traceback.print_exc()
         for id in ids:
             tmp.append(Entity(id, 0, '', 0.0, 0))
         return tmp
     if ens is None:
         LOG_NOTE('players are None')
     else:
         for id, info in ens.iteritems():
             id = int(id)
             if info is not None:
                 pr = int(getNestedElement(info, self.formatz['pr_index']))
                 bt = int(
                     getNestedElement(info, self.formatz['battles_index']))
                 wr = int(getNestedElement(info, self.formatz['wr_index']))
                 if not bt:
                     wr = 0.0
                 else:
                     wr = wr * 100.0 / bt
                 lang = getNestedElement(info, self.formatz['lang_index'])
                 entity = Entity(id, pr, lang, wr, bt)
                 tmp.append(entity)
             else:
                 tmp.append(Entity(id, 0, '', 0.0, 0))
     return tmp
示例#6
0
    def place_entities(self, room, entities, max_monsters_per_room,
                       max_items_per_room):
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)

        for i in range(number_of_monsters):
            # Chooses a random location in a room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                if randint(0, 100) < 80:
                    fighter_component = Fighter(hp=10, defense=0, power=3)
                    ai_component = BasicMonster()

                    monster = Entity(x,
                                     y,
                                     'o',
                                     libtcod.desaturated_green,
                                     'Orc',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)
                else:
                    fighter_component = Fighter(hp=16, defense=1, power=4)
                    ai_component = BasicMonster()
                    monster = Entity(x,
                                     y,
                                     'T',
                                     libtcod.darker_green,
                                     'Troll',
                                     blocks=True,
                                     render_order=RenderOrder.ACTOR,
                                     fighter=fighter_component,
                                     ai=ai_component)

                entities.append(monster)

        for i in range(number_of_items):
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([
                    entity
                    for entity in entities if entity.x == x and entity.y == y
            ]):
                item_component = Item()
                item = Entity(x,
                              y,
                              '!',
                              libtcod.violet,
                              'Healing Potion',
                              render_order=RenderOrder.ITEM,
                              item=item_component)

                entities.append(item)
示例#7
0
 def place_entities(self, room, entities, max_monsters_per_room):
     number_of_monsters = randint(0, max_monsters_per_room)
     for i in range(number_of_monsters):
         x = randint(room.x1 + 1, room.x2 - 1)
         y = randint(room.y1 + 1, room.y2 - 1)
         if not any([
                 entity
                 for entity in entities if entity.x == x and entity.y == y
         ]):
             if randint(0, 100) < 80:
                 fighter_component = Fighter(hp=10, defense=0, power=3)
                 ai_component = BasicMonster()
                 monster = Entity(x,
                                  y,
                                  'o',
                                  libtcod.desaturated_green,
                                  'Orc',
                                  blocks=True,
                                  fighter=fighter_component,
                                  ai=ai_component)
             else:
                 fighter_component = Fighter(hp=16, defense=1, power=4)
                 ai_component = BasicMonster()
                 monster = Entity(x,
                                  y,
                                  'Y',
                                  libtcod.darker_green,
                                  'Troll',
                                  blocks=True,
                                  fighter=fighter_component,
                                  ai=ai_component)
             entities.append(monster)
示例#8
0
 def __init__(self,name,health,attack):
     self.pos = [0,0]
     self.name = name
     self.health = health
     self.attack = attack
     self.defense = 2
     self.inventory = [Entity("a stick","item",2,2),\
                         Entity("rags","item",2,2)]
     self.weapon = Entity("a stick","item",2,2)
     self.armor = Entity("rags","item",2,2)
 def from_file(cls, filepath):
     relations = []
     lines = open(filepath).readlines()
     for line in lines:
         j = json.loads(line)
         r = Relation(**j)
         r.entity1 = Entity(**r.entity1)
         r.entity2 = Entity(**r.entity2)
         relations.append(r)
     return RelationCollection(relations)
示例#10
0
class Entities:
    @staticmethod
    def genNewPlayerProjectile():
        return Entity("|", Config.PLAYER_COLOR, EntityType.PLAYER_PROJECTILE)

    # TODO: Implement player and enemy projectiles.
    PLAYER: Entity = Entity(Config.PLAYER_SYMBOL, Config.PLAYER_COLOR,
                            EntityType.PLAYER)
    ENEMIES: List[Entity] = [
        Entity(Config.ENEMY_SYMBOL, color, EntityType.ENEMY)
        for color in Config.ENEMY_COLORS
    ]
示例#11
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150)
    }

    player = Entity(int(screen_width / 2), int(screen_height / 2), '@', libtcod.white)
    npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), '@', libtcod.yellow)
    entities = [npc, player]

    libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'RogueLike Game Example', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        render_all(con, entities, game_map, screen_width, screen_height, colors)
        libtcod.console_set_default_foreground(0, libtcod.white)

        libtcod.console_flush()

        clear_all(con, entities)
        libtcod.console_put_char(0, player.x, player.y, ' ', libtcod.BKGND_NONE)
        
        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move
            player.move(dx, dy)

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
示例#12
0
    def testSample(self):
        testSystem = TestSystem()
        world = World([testSystem], [])

        testEntity = Entity()
        testEntity.id = 0
        world.entities.append(testEntity)

        testEntity2 = Entity()
        testEntity2.id = "This id should print too"
        world.entities.append(testEntity2)

        world.processSystems()
示例#13
0
def crossover(mum, dad):
    # Copy parents if crossover rate doesn't pass,
    # or if same parent was selected as both mum and dad.
    if random.uniform(0, 1) > Params.crossover_rate or mum == dad:
        child_one = Entity()
        child_two = Entity()
        child_one.brain.replace_weights(mum.brain.get_weights())
        child_two.brain.replace_weights(dad.brain.get_weights())

        return child_one, child_two
    print("Crossover happened")

    # If crossover happens, randomly select each weight from either mum or dad
    #parent_weights = (mum.brain.get_weights(), dad.brain.get_weights())

    child_one = Entity()
    child_two = Entity()

    child_one_weights = []
    child_two_weights = []

    # Determine crossover point
    # crossover_point = random.randint(0, mum.brain.get_number_of_weights() - 1)

    swap_crossover = False

    # For each layer
    for i in range(Params.num_hidden_layers + 1):
        # For each neuron
        for j in range(mum.brain.layers[i].num_neurons):
            # Crossover for each neuron. Children cris-cross for each neuron between parents.
            swap_crossover = not swap_crossover

            # For each weight
            for k in range(mum.brain.layers[i].neurons[j].num_inputs):
                if swap_crossover:
                    child_one_weights.append(
                        mum.brain.layers[i].neurons[j].input_weights[k])
                    child_two_weights.append(
                        dad.brain.layers[i].neurons[j].input_weights[k])
                else:
                    child_one_weights.append(
                        dad.brain.layers[i].neurons[j].input_weights[k])
                    child_two_weights.append(
                        mum.brain.layers[i].neurons[j].input_weights[k])

    # Put the weights into the children
    child_one.brain.replace_weights(child_one_weights)
    child_two.brain.replace_weights(child_two_weights)

    return child_one, child_two
示例#14
0
    def test_collision_fail(self):
        arena = Arena()

        entity1 = Entity()
        entity1.x = 1
        entity1.y = 1

        entity2 = Entity()
        entity2.x = 1
        entity2.y = 2

        arena.add_static(entity1)
        arena.add_static(entity2)

        arena.process_collisions()
示例#15
0
文件: World.py 项目: MWojnar/GMTK2
 def loadMenu(self):
     self.entityList.clear()
     self.addEntity(self.cursor)
     self.cursor.visible = True
     self.level = 1
     tutorial = Entity(self, self.screenWidth / 2, self.screenHeight / 2, self.assetLoader.tutorial)
     self.addEntity(tutorial)
     wojWorks = Entity(self, self.screenWidth / 2, self.assetLoader.wojWorks.height / 2 - 20, self.assetLoader.wojWorks)
     self.addEntity(wojWorks)
     title = Entity(self, self.screenWidth / 2, self.screenHeight / 4 + 52, self.assetLoader.title)
     self.addEntity(title)
     startButton = Button(self, self.screenWidth / 2, self.screenHeight / 2 + 48, self.assetLoader.start, self.assetLoader.startSelected, self.start, self.cursor)
     self.addEntity(startButton)
     quitButton = Button(self, self.screenWidth / 2, self.screenHeight * 3 / 4, self.assetLoader.quit, self.assetLoader.quitSelected, exit, self.cursor)
     self.addEntity(quitButton)
示例#16
0
def create_mob_entity(x,
                      y,
                      mob_index,
                      encounter,
                      ai_type=AI,
                      faction_name="Mindless"):
    mob_stats = MOBS.get(mob_index)
    faction_component = Faction(faction_name=faction_name)
    fighter_component = Fighter(hp=mob_stats.get('hp'),
                                defense=mob_stats.get('def'),
                                power=mob_stats.get('att'),
                                xp=mob_stats.get('xp'),
                                fov_range=mob_stats.get('fov_range'),
                                mob_level=mob_stats.get('mob_level'))
    ai_component = ai_type(encounter=encounter, origin_x=x, origin_y=y)
    position_component = Position(x, y)
    mob_entity = Entity(mob_stats.get('glyph'),
                        mob_stats.get('color'),
                        mob_stats.get('name'),
                        json_index=mob_index,
                        position=position_component,
                        blocks=True,
                        fighter=fighter_component,
                        render_order=RenderOrder.ACTOR,
                        ai=ai_component,
                        faction=faction_component)
    return mob_entity
 def getPersonEntities(self):
     entities = set()
     for ent in self.docs.ents:
         e = Entity(ent.text, ent.start_char, ent.end_char, ent.label_)
         if e.isPerson():
             entities.add(e.getWord())
     return list(entities)
示例#18
0
def Assemble_Text_Box(sEntityName, sEntityType, iDrawPriority, attribDict):
    """This assembles a box with text in it!"""
    entity = Entity(sEntityName, sEntityType, iDrawPriority, {})

    #The first argument represents the ID of the component with respect to its type (multiple components of a single type need to have different IDs.)
    entity._Add_Component(
        getClass("Box")({
            'componentID': '0',
            'x': attribDict['x'],
            'y': attribDict['y'],
            'width': attribDict['width'],
            'height': attribDict['height']
        }))
    entity._Add_Component(
        getClass("Text_Line")({
            'componentID': "0",
            'x': attribDict['x'],
            'y': attribDict['y'],
            'width': attribDict['width'],
            'height': attribDict['height'],
            'text': attribDict['text'],
            'font': attribDict["Font"]["Asman"]
        }))

    return entity
示例#19
0
文件: PullOrb.py 项目: MWojnar/GMTK2
 def __init__(self,
              world=None,
              x=0,
              y=0,
              sprite=None,
              depth=-2,
              player=None,
              cursor=None):
     super().__init__(world, x, y, depth=depth)
     if sprite == None:
         self.sprite = world.assetLoader.pullOrb
     else:
         self.sprite = sprite
     self.player = player
     self.range = 175
     self.circleMaskRadius = 32
     self.pullOrbTether = PullOrbTether(world,
                                        pullOrb=self,
                                        player=player,
                                        depth=depth - 1)
     world.addEntity(self.pullOrbTether)
     pullOrbRange = Entity(world, x, y, self.world.assetLoader.pullRange,
                           depth - 2)
     world.addEntity(pullOrbRange)
     self.cursor = cursor
示例#20
0
    def test_collision_pass(self):
        arena = Arena()

        entity1 = Entity()
        entity1.x = 1
        entity1.y = 1

        entity2 = Entity()
        entity2.x = 1
        entity2.y = 1

        arena.add_static(entity1)
        arena.add_static(entity2)

        with self.assertRaises(Collision):
            arena.process_collisions()
示例#21
0
    def extractentities(self, text):
        doc = self.nlp(text)
        entities = []
        for X in doc.ents:
            if X.text != ('\n') and X.label_ in ('PERSON', 'ORG', 'LOC',
                                                 'DATE', 'MONEY', 'GPE'):
                print(X.text, X.label_)
                entity = X.text
                entity = re.sub('[^A-Za-z0-9]+', '', entity)
                n1 = entity.replace("\t", " ")
                n2 = n1.replace("\r", " ")
                n3 = n2.replace("\n", " ")
                finaltext = n3.replace("\u00a0", " ")
                finaltext_ = finaltext.replace("\xa0", " ")
                finaltext_.lstrip(" ")
                finaltext_.rstrip(" ")
                entity = finaltext_

                if (entity.lower() in stop_words or entity in " "
                        or entity in "_" or entity.isdigit()
                        or not self.verify(entity)):
                    print("Entity Skipped")
                else:
                    entity_ = Entity(entity, X.label_)
                    entities.append(entity_)
                    self.entitiesall.append(X.text)
                    if (not self.isAlreadyThere(self.uniqueentities, entity)):
                        self.uniqueentities.append(entity)
                    if (X.label_ == 'PERSON'):
                        self.personEntities.append(entity)
                    elif (X.label_ == 'ORG'):
                        self.orgEntities.append(entity)
        return entities
示例#22
0
def entity_data(request):
    """ """
    site = request.matchdict['code']
    claims, site = verify_access(request, site=site)
    e = Entity(request)
    summnote, fullnote = e.data()
    return {'summnote': summnote, 'fullnote': fullnote}
示例#23
0
 def spawnNew(self, id, name, x, y):
     print("Spawning entity: {0} ({1},{2})".format(name, x, y))
     entity = Entity(self, id, name, x, y)
     entity.start()
     self.send_entity_create(id, name, x, y)
     self.entities.append(entity)
     self.eCurId += 1
示例#24
0
def Assemble_Button(sEntityName, sEntityType, iDrawPriority, attribDict):
    """This assembles a box with text in it! And sets up some other
    components that'll store important information we might need later."""
    entity = Entity(sEntityName, sEntityType, iDrawPriority, {})

    entity._Add_Component(
        getClass("Box")({
            'componentID': '0',
            'x': attribDict['x'],
            'y': attribDict['y'],
            'width': attribDict['width'],
            'height': attribDict['height']
        }))
    entity._Add_Component(
        getClass("Text_Line")({
            'componentID': '0',
            'x': attribDict['x'],
            'y': attribDict['y'],
            'width': attribDict['width'],
            'height': attribDict['height'],
            'text': attribDict['text'],
            'font': attribDict['Font']["Asman"]
        }))
    entity._Add_Component(
        getClass("Flag")({
            'componentID': '0',
            'flag': False
        }))

    return entity
示例#25
0
文件: World.py 项目: ncolliou/NSI
 def __init__(self, data, game):
     # liste qui sauvegarde les blocks avec leurs positions
     self.tile_list = {}
     self.data = data
     self.game = game
     # chargements images
     self.dirt_img = pygame.image.load(dirt_block_path_img)
     self.grass_img = pygame.image.load(grass_block_path_img)
     self.stone_img = pygame.image.load(stone_block_path_img)
     self.log_img = pygame.image.load(log_block_path_img)
     self.leaves_img = pygame.image.load(leaves_block_path_img)
     self.bedrock_img = pygame.image.load(bedrock_block_path_img)
     self.tallgrass_img = pygame.image.load(tallgrass_block_path_img)
     self.coal_img = pygame.image.load(coal_block_path_img)
     self.planks_img = pygame.image.load(planks_block_path_img)
     # utiliser dans l'inventaire et la hotbar
     self.blocks_img = {
         "dirt": pygame.transform.scale(self.dirt_img, (39, 39)),
         "grass": pygame.transform.scale(self.grass_img, (39, 39)),
         "stone": pygame.transform.scale(self.stone_img, (39, 39)),
         "log": pygame.transform.scale(self.log_img, (39, 39)),
         "leaves": pygame.transform.scale(self.leaves_img, (39, 39)),
         "tallgrass": pygame.transform.scale(self.tallgrass_img, (39, 39)),
         "coal": pygame.transform.scale(self.coal_img, (39, 39)),
         "planks": pygame.transform.scale(self.planks_img, (39, 39))
     }
     self.decalagex = 0
     self.decalagey = 0
     self.cow = Entity(self, "cow", 120, 480 + self.data[2] - 89,
                       pygame.image.load(cow_path_img), True)
     self.dec = -250
示例#26
0
def place_stairs(game_map, dungeon_level, x, y):
    object_index = "11"
    object_stats = TILE_SET.get(object_index)

    movable = object_stats.get('moveable')
    breakable = object_stats.get('breakable')
    walkable = object_stats.get('walkable')
    properties = object_stats.get('properties')

    position_component = Position(x, y)
    map_object_component = MapObject(
        name=object_stats.get('name'),
        movable=movable,
        breakable=breakable,
        walkable=walkable,
        properties=properties,
        interact_function=eval(
            object_stats.get('interact_function', "no_function")),
        wait_function=eval(object_stats.get("wait_function", "no_function")))

    stairs_entity = Entity(object_stats.get("char"),
                           object_stats.get("color"),
                           object_stats.get("name"),
                           furniture=map_object_component,
                           json_index=object_index,
                           position=position_component,
                           render_order=RenderOrder.STAIRS,
                           stairs=Stairs(dungeon_level + 1))
    game_map.map_objects.append(stairs_entity)
    place_tile(game_map, x, y, object_index)
    game_map.stairs = stairs_entity
示例#27
0
def generate_particle(x, y, particle_index):
    p_stats = PARTICLES.get(particle_index)
    p_name = p_stats.get("name")
    p_lifetime = p_stats.get("lifetime")
    p_char = p_stats.get("glyph")
    p_fg = p_stats.get("fg")
    p_bg = p_stats.get("bg")
    p_propagate = p_stats.get("propagate", False)
    p_propagate_property = p_stats.get("propagate_property", None)
    p_forever = p_stats.get("forever", False)
    position_component = Position(x=x, y=y)
    particle_component = Particle(lifetime=p_lifetime,
                                  char=p_char,
                                  fg=p_fg,
                                  bg=p_bg,
                                  forever=p_forever,
                                  propagate=p_propagate,
                                  propagate_property=p_propagate_property)
    particle_entity = Entity(char=p_char,
                             color=p_fg,
                             name=p_name,
                             json_index=particle_index,
                             position=position_component,
                             particle=particle_component,
                             render_order=RenderOrder.PARTICLE)

    return particle_entity
示例#28
0
def temp_main():
	transactions_dict = populate_transactions_dict()
	TH = TransactionHandler()
	me = TH.get_entity("Me")
	tc, ti = float("inf"), 0
	# print("transactions_dict {td}".format(td=transactions_dict))
	print("\tReport\n", TH.costing_report(me, "Annually"))
	for num, transaction in transactions_dict.items():
		# amount, entity_from, entity_to, reoccurring_category, transaction_catgory, description, date_in
		# Transaction Date, Transaction Amount, Notes, Transaction Type, Entity
		amount = float(transaction["Transaction Amount"])
		entity = Entity(unclutter(transaction["Entity"]))
		transaction_type = transaction["Transaction Type"]
		date = transaction["Transaction Date"]
		# TODO: if if there is no reason to use a dict here, then change to a list
		transaction = {
			"amount": abs(amount),
			"entity_from": me if amount < 0 else entity,
			"entity_to": me if amount > 0 else entity,
			"reoccurring_category": "Once",
			"transaction_category": transaction_type,
			"description": entity,
			"date_in": date
		}
		# print("transaction: {t}".format(t=list(transaction.values())))
		transaction = TH.create_transaction(*list(transaction.values()))
		TH.add_transaction(transaction)
		ti += 1
		if ti == tc:
			break
	print("TH.transaction_list:", TH.transaction_list)
	print(dict_print(dict(zip(range(1, 1 + len(TH.transaction_list)), [tl.info_dict() for tl in TH.transaction_list])), "Transactions"))
class Borders:
    VERTICAL = Entity("║", Colors.WHITE, EntityType.BORDER)
    HORIZONTAL = Entity("═", Colors.WHITE, EntityType.BORDER)
    TOP_LEFT = Entity("╔", Colors.WHITE, EntityType.BORDER)
    TOP_RIGHT = Entity("╗", Colors.WHITE, EntityType.BORDER)
    BOT_LEFT = Entity("╚", Colors.WHITE, EntityType.BORDER)
    BOT_RIGHT = Entity("╝", Colors.WHITE, EntityType.BORDER)
    INTERSECT_LEFT = Entity("╠", Colors.WHITE, EntityType.BORDER)
    INTERSECT_RIGHT = Entity("╣", Colors.WHITE, EntityType.BORDER)
示例#30
0
    def crawl_search_results(self):
        search_results = []

        try:
            self.wait.until(ec.presence_of_element_located((By.ID, 'searchlist')))
        except TimeoutException:
            CustomLogging.log_to_file('第一财经网搜索结果页错误', LogType.ERROR)

        exit_flag = 0
        start_index = 0
        while True:
            try:
                self.wait.until(ec.presence_of_all_elements_located((By.CLASS_NAME, 'f-db')))
            except TimeoutException:
                CustomLogging.log_to_file('文章列表加载失败', LogType.ERROR)
                break

            try:
                result_articles = self.driver.find_elements_by_class_name('f-db')

                for each_article in result_articles[start_index:]:
                    item = Entity()
                    item.publish_date = \
                        each_article.find_element_by_class_name('author').find_elements_by_tag_name('span')[
                            -1].text

                    if not in_date_range(conv_pub_date(item.publish_date, 'yicai'), self.year_range):
                        exit_flag = 1
                        # 跳出for循环
                        break
                    item.title = each_article.find_element_by_tag_name('h2').text
                    item.short_description = each_article.find_element_by_tag_name('p').text

                    if self.keyword not in item.title and self.keyword not in item.short_description:
                        continue

                    item.url = each_article.get_attribute('href')
                    threading.Thread(target=self.download_and_save_item, args=(item,)).start()

                if exit_flag == 1:
                    break

            except NoSuchElementException:
                CustomLogging.log_to_file('没有搜索结果', LogType.ERROR)
                pass

            try:
                # next_page = self.wait.until(ec.visibility_of_element_located(
                #     (By.XPATH, '//button[@class="u-btn" and contains(text(), "加载更多内容")]')))
                # next_page = self.driver.find_element_by_xpath('//button[@class="u-btn" and contains(text(), "加载更多内容")]')
                # next_page.click()
                self.driver.execute_script('document.getElementsByClassName("u-btn")[0].click()')
                time.sleep(2)
                start_index += 20
            except TimeoutException:
                CustomLogging.log_to_file('全部页面加载完成', LogType.INFO)
                break

        return search_results