首页 > 解决方案 > 通过里面的元素文本找到 div 类

问题描述

我正在抓取一个游戏网站,我想获取包含特定文本的 div 对象。在这种情况下,我想获取包含带有文本“SANDBOX Ghost”的 href 的 div 类“GameItemWrap”。整个代码中有许多 GameItemWrap 类,我不想获取“SummonerName”类 div,因为“GameItemWrap”中还有一些我需要的其他类。

这是我尝试过的:

duo_name='SANDBOX Ghost'    
gamelist=soup.find('div',"GameItemList")# "GameItemList" is a div that contains "GameItemWrap"
games=gamelist.find_all('GameItemWrap',{('a'):duo_name })

这就是我正在抓取的 javascript 的样子:

<div class="GameItemWrap>
    #some other div classes that i will need in the future 
    <div class="SummonerName">                                                       
        <a href="//www.op.gg/summoner/userName=SANDBOX+Ghost" class="Link" target="_blank">SANDBOX Ghost</a>                                                 
    </div>
</div>

我期待 4 个包含文本“SANDBOX Ghost”的 GameItemWrap,但是当我打印时

print(len(games)) 

输出为 0。这不起作用。另外我不想检查每一个 GameItemWraps 类来检查它们是否包含“SANDBOX Ghost”这可能吗?

标签: pythonweb-scrapingbeautifulsoup

解决方案


希望您的目标数据出现在标签上,然后尝试像下面这样使用,这将对您有所帮助。

duo_name='SANDBOX Ghost'
games = soup.find_all('a',string=duo_name)

完整的代码看起来像,

from bs4 import BeautifulSoup
import re
chunk = '''<div class="GameItemWrap">
    #some other div classes that i will need in the future
    <div class="SummonerName">
        <a href="//www.op.gg/summoner/userName=SANDBOX+Ghost" class="Link" target="_blank">SANDBOX Ghost</a>
    </div>
</div>'''
soup = BeautifulSoup(chunk,'html5lib')
game_data = {}
duo_name='SANDBOX Ghost'
for chunks in soup.find_all('div',{'class':'GameItemWrap'}):
    if chunks.find('a',string=duo_name):
        chunk_for_future = chunks
        a_tag = chunks.find('a',string=duo_name)
        game_data[a_tag.text] = a_tag['href']
print(game_data)

你的结果将是(在字典中说明),

{'SANDBOX Ghost': '//www.op.gg/summoner/userName=SANDBOX+Ghost'}

推荐阅读