【问题标题】:Understand the Find() function in Beautiful Soup了解 Beautiful Soup 中的 Find() 函数
【发布时间】:2016-03-21 23:41:04
【问题描述】:

我知道我想做的很简单,但这让我很伤心。我想使用 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=7359973599,来自data-value=3245232352,以及来自percentage good69%

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

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

到目前为止,两者都没有效果。我不确定如何制作查找以提取69% 号码。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    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)
    

    【讨论】:

    • 太棒了!这正是我想要的。案件结案。
    • 对于那些和我犯过同样错误的人来说,传递给soup.find()的参数需要双引号。
    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2015-02-04
    • 2023-03-24
    相关资源
    最近更新 更多