【问题标题】:find div class by the element text inside it通过里面的元素文本找到 div 类
【发布时间】:2019-05-21 03:45:50
【问题描述】:

我正在抓取一个游戏网站,我想获取包含特定文本的 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” 这可能吗?

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

修复显示的 html 后,使用 bs4 4.7.1 我希望您能够使用 :contains 伪类

from bs4 import BeautifulSoup as bs

html ='''
<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>
'''
duo_name = 'SANDBOX Ghost'
soup = bs(html, 'lxml') #'html.parser' if lxml not installed
items = soup.select('.GameItemWrap:contains("' + duo_name + '")')

【讨论】:

    【解决方案2】:

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

    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'}
    

    【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签