【问题标题】:Parsing specific part of class解析类的特定部分
【发布时间】:2020-09-23 10:40:53
【问题描述】:

我想从一个 html 文档类中进行解析,但前提是该类中包含特定的单词。所以例如在

<div class="article-xyz"> or <div class="abcd-xyzefg"> 

这个 Python 代码

from bs4 import BeautifulSoup

with open('simple2.html') as html_file:
    soup = BeautifulSoup(html_file, 'lxml')

article_all = soup.find_all('div', class_='xyz')

如果我搜索“xyz”,应该会提取一些结果,但它不会。

这是我的测试 html:

<!doctype html>
<html class="no-js" lang="">
    <head>
        <title>Test - A Sample Website</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <h1 id='site_title'>Test Website</h1>
        <hr></hr>
        <div class="article">
            <h2><a href="article_1.html">Article 1 Headline</a></h2>
            <p>This is a summary of article 1</p>
        </div>
        <hr></hr>
        <div class="article">
            <h2><a href="article_2.html">Article 2 Headline</a></h2>
            <p>This is a summary of article 2</p>
        </div>
        <hr></hr>
        <div class="article-xyz">
            <h2><a href="article_2.html">Article 2 test headline dings</a></h2>
            <p> article 2 test thing</p>
        </div>
        <div class='footer'>
            <p>Footer Information</p>
        </div>
        <div class="other-xyz-stuff">
            <h2><a href="article_2.html">other-xyz-stuff test headline </a></h2>
            <p>other-xyz-stuff test </p>
        </div>
        <script src="js/vendor/modernizr-3.5.0.min.js"></script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

到目前为止,我正在使用带有 BS4 的 Python 3.7。

谁能帮帮我?

谢谢你和问候

【问题讨论】:

标签: python parsing web-scraping beautifulsoup html-parsing


【解决方案1】:

像使用 lambda 一样

article_all = soup.find_all('div', class_=lambda x: x and 'xyz' in x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多