【发布时间】:2019-01-09 18:03:01
【问题描述】:
在 BeautifulSoup4 中,如何搜索包含特定字符串的文本标签?例如,在搜索“天际”时,我想打印包含字符串“天际”的每个标签的内容(例如游戏标题)。
我试过了
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>, ...]
预期结果:
- 上古卷轴 V:天际特别版
- 天际脚本扩展器 (SKSE)
实际结果:不打印任何东西
【问题讨论】:
-
试试 getText() 方法。 tag.getText()
-
提及
steam_results的数据。 -
getText() 导致同样的错误。
-
现在看来不错了。
标签: python web-scraping beautifulsoup python-requests