python - 了解 Beautiful Soup 中的 Find() 函数

标签 python html beautifulsoup

我知道我想做的很简单,但这让我很伤心。我想使用 BeautifulSoup 从 HTML 中提取数据。为此,我需要正确使用 .find() 函数。这是我正在使用的 HTML:

<div class="audit">

    <div class="profile-info">
        <img class="profile-pic" src="https://pbs.twimg.com/profile_images/471758097036226560/tLLeiOiL_normal.jpeg" />
        <h4>Ed Boon</h4>
        <span class="screen-name"><a href="http://www.twitter.com/noobde" target="_blank">@noobde</a></span>
    </div>

        <div class="followers">
            <div class="pie"></div>
            <div class="pie-data">
                <span class="real number" data-value=73599>73,599</span><span class="real"> Real</span><br />
                <span class="fake number" data-value=32452>32,452</span><span class="fake"> Fake</span><br />
                <h6>Followers</h6>
            </div>
        </div>
        <div class="score">
            <img src="//twitteraudit-prod.s3.amazonaws.com/dist/f977287de6281fe3e1ef36d48d996fb83dd6a876/img/audit-result-good.png" />
            <div class="percentage good">
                69%
            </div>
            <h6>Audit score</h6>

我想要的值是data-value=7359973599data-value=3245232352 >,以及来自 percentage good69%

使用过去的代码和在线示例,这是我目前所拥有的:

RealValue = soup.find("div", {"class":"real number"})['data-value']
FakeValue = soup.find("audit", {"class":"fake number"})['data-value']

到目前为止都没有效果。我不确定如何制作查找以提取 69% 数字。

最佳答案

soup.find("div", {"class":"real number"})['data-value']

您在此处搜索 div 元素,但 span 在示例 HTML 数据中具有“实数”类,请尝试:

soup.find("span", {"class": "real number", "data-value": True})['data-value']

这里我们还检查是否存在 data-value 属性。


要查找具有“实数”或“假数”类的元素,您可以制作 CSS selector :

for elm in soup.select(".real.number,.fake.number"):
    print(elm.get("data-value"))

获取 69% 值:

soup.find("div", {"class": "percentage good"}).get_text(strip=True)

或者,一个 CSS 选择器:

soup.select_one(".percentage.good").get_text(strip=True)
soup.select_one(".score .percentage").get_text(strip=True)

或者,找到包含 Audit score 文本的 h6 元素,然后获取 preceding sibling :

soup.find("h6", text="Audit score").previous_sibling.get_text(strip=True)

关于python - 了解 Beautiful Soup 中的 Find() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301815/

相关文章:

python - 最大的python项目

html - 跨浏览器字母间距

html - 提高 BeautifulSoup 解析速度

python - 使用 Beautiful Soup 提取特定列表项

javascript - 为什么使用 jQuery .replace 会导致网页未找到错误?

python - BeautifulSoup 的编码问题

python - 从一个 Pandas 系列中减去另一个 Pandas 系列而不为缺失数据创建 NaN 值

python - 在 tf.keras 中正确设置 GAN 实现中的 .trainable 变量

Python 3.3内部嵌套While循环不输出

java - 使用Jsoup获取没有属性的元素