在BeautifulSoup4中,如何搜索包含特定字符串的文本标记?例如,在搜索“skyrim”时,我想打印包含字符串“skyrim”的每个标签的内容(例如游戏标题)。你知道吗
我试过用
if 'skyrim' in tag.string:
但它从不打印任何东西。你知道吗
完整定义:
def search(self):
steam_results = self.soup.find_all('span', class_='title')
itr = 1
for tag in steam_results:
if self.title in tag.string: # <--- Not working
print(str(itr) + ': ' + tag.string + '\n')
itr = itr + 1
steam_results
样本:
>>> steam_results
[<span class="title">The Elder Scrolls V: Skyrim Special Edition</span>,
<span class="title">Skyrim Script Extender (SKSE)</span>,
<span class="title">Enderal</span>, ...]
预期结果:
实际结果:不打印任何内容
问题是子字符串检查,因为它是
case-sensitive
。如果使用skyrim
进行检查,将得到空结果,因为没有title
包含skyrim
,而是包含Skyrim
。所以,把它和小写的标题比较一下输出:
可以使用
soup.find_all(string=re.compile("your_string_here")
获取文本,然后使用.parent
获取标记。你知道吗输出
相关问题 更多 >
编程相关推荐