python - 在python中使用beautifulsoup提取网页的数据丰富节点

标签 python python-2.7 tags web-scraping beautifulsoup

在python中使用beautifulsoup提取网页的数据丰富节点,有没有办法统计页面中标签的频率,

import requests
from bs4 import BeautifulSoup

url = "http://www.amazon.in"
r = requests.get(url)

html = BeautifulSoup(r.content)

现在我想统计获得的html中所有标签的频率。

最佳答案

使用dict comprehensionscollection.Counter获取作为 bs4.element.Tag 实例的 tags 数量。

from collections import Counter
import requests
import bs4
from bs4 import BeautifulSoup
url = "http://www.amazon.in"
r = requests.get(url)
html = BeautifulSoup(r.content)
Counter(tag.name for tag in html.descendants if isinstance(tag, bs4.element.Tag))

输出

Counter({'div': 462, 'a': 448, 'span': 395, 'li': 288, 'br': 78, 'img': 60, 'td': 57, 'script': 48, 'ul': 39, 'option': 27, 'tr': 22, 'table': 17, 'meta': 13, 'map': 12, 'area': 12, 'link': 11, 'style': 10, 'p': 10, 'b': 9, 'h2': 7, 'strong': 5, 'input': 2, 'body': 1, 'title': 1, 'html': 1, 'header': 1, 'form': 1, 'head': 1, 'label': 1, 'select': 1})

关于python - 在python中使用beautifulsoup提取网页的数据丰富节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29777794/

相关文章:

Python - 查找一个数字,然后从字符串中复制它

python - 图形中的模式匹配

javascript - 在 javascript 中更改没有 id 的文本 b/n Span 标记

java - Lucene索引没有html css标签java

python - 为什么python -c "print float(7/3)"打印出2.0

python - 如何识别广播消息?

python - Pycharm环境不同于命令行

python - 带有 except block 的变量范围 : Difference between Python 2 and 3

python-2.7 - Python 电子邮件模块 ImportError : No module named utils

c# - 如何在 C# 中应用多个 .Tag 属性?