python - 通过里面的元素文本找到 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”这可能吗?
解决方案
希望您的目标数据出现在标签上,然后尝试像下面这样使用,这将对您有所帮助。
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'}
推荐阅读
- c++ - 如何在允许运行时调用的同时保证算法的编译时评估
- react-native - 如何在滚动视图中实现scrollToEnd函数反应原生
- java - 如何在 Java 11 中使用不受支持的语言环境和 String.format() 中的数字
- utf-8 - MacOS Big Sur:意外的差异行为
- maven - Maven 命令找不到任何测试
- ruby-on-rails - Rails/RSpec - 如何为处理程序编写 rspec 测试?
- postgresql - 服务器停止后 Postgres 数据仍在“使用中”
- rust - 枚举如何使用堆或堆栈类型处理其子类型?
- c# - 如何在 SQL 中插入 1M 模型
- ios - iOS 上的 Firebase Realtime:无法访问实时数据库