首页 > 解决方案 > 使用 BeautifulSoup 的 HTML 页面中的子字符串计数

问题描述

我需要使用 BeautifulSoup 模块在 HTML 代码中查找并计算所有“python”和“c++”单词作为子字符串。在维基百科中,这些词相应地出现了 1 次和 9 次。为什么我的代码写 0 和 0?

from urllib.request import urlopen, urlretrieve

from bs4 import BeautifulSoup


resp = urlopen("https://stepik.org/media/attachments/lesson/209717/1.html") 

html = resp.read().decode('utf8') 

soup = BeautifulSoup(html, 'html.parser') 

table = soup.find('table', attrs = {'class' : 'wikitable sortable'})

cnt = 0

for tr in soup.find_all("python"):

    cnt += 1

print(cnt)

cnt1 = 0

for tr in soup.find_all("c++"):

    cnt += 1

print(cnt)

标签: pythonhtmlbeautifulsoup

解决方案


你做错了你需要使用字符串参数来搜索任何字符串

    
    # These will only work in case like these <b>Python</b>
    soup.find_all(string="Python")

    # Not in these <b>python</b> or <b>Python is best</b>
    #We can use regex to fix that they will work in substring cases 
    
    soup.find_all(string=re.compile("[cC]\+\+")) 
    soup.find_all(string=re.compile("[Pp]ython"))

推荐阅读