python - 使用 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)
解决方案
你做错了你需要使用字符串参数来搜索任何字符串
# 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"))
推荐阅读
- java - 为什么 maven 从命令行执行配置文件时出错
- java - Intellij IDE 在 gradle 项目中看不到生成的类
- java - 如何在我的 java webapp 中使用 api 与另一个 webapp 通信?
- amazon-web-services - AWS CloudFormation - 资源未能创建错误
- java - java中数字的正则表达式
- javascript - 如何生成批量二维码
- javascript - 取消注释 jquery 如何导致 Rails 服务器工作?
- r - 在四个数据框列上应用两个不同的公式
- c# - 从 Web Api 返回计算结果的正确方法
- python-3.x - 如何在 Python 中使用两条 grep 行