【问题标题】:How do I search for tags in BS4 containing a given string?如何在 BS4 中搜索包含给定字符串的标签?
【发布时间】: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>, ...]

预期结果:

  1. 上古卷轴 V:天际特别版
  2. 天际脚本扩展器 (SKSE)

实际结果:不打印任何东西

【问题讨论】:

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

问题是子字符串检查,因为它是case-sensitive。如果您检查skyrim,您将得到空结果,因为没有title 包含skyrim,而是它们包含Skyrim。所以,把它和像这样的小写标题比较一下,

steam_results = soup.find_all('span', class_='title')
for steam in steam_results:
    if 'skyrim' in steam.getText().lower():
        print(steam.getText())

输出:

The Elder Scrolls V: Skyrim Special Edition
The Elder Scrolls V: Skyrim VR
Skyrim Script Extender (SKSE)
The Elder Scrolls V: Skyrim Special Edition - Creation Club

【讨论】:

  • 或者,建议进行不区分大小写的测试,例如if 'skyrim' in steam.getText().lower():,以便将所有内容转换为小写并进行比较。
  • 感谢您的好建议。
【解决方案2】:

您可以使用soup.find_all(string=re.compile("your_string_here")获取文本,然后使用.parent获取标签。

from bs4 import BeautifulSoup
import re
html="""
<p id="1">Hi there</p>
<p id="2">hello<p>
<p id="2">hello there<p>
"""
soup=BeautifulSoup(html,'html.parser')
print([tag.parent for tag in soup.find_all(string=re.compile("there"))])

输出

[<p id="1">Hi there</p>, <p id="2">hello there<p>\n</p></p>]

【讨论】:

    猜你喜欢
    • 2015-10-14
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多