【问题标题】:Extracting the text from some HTML tags从一些 HTML 标签中提取文本
【发布时间】:2020-02-21 17:02:18
【问题描述】:

我正在使用 BeautifulSoup 在职业页面上抓取职位列表。我无法打印出我需要的信息。

这是 HTML 的样子

<ul class="list-group">
<li class="list-group-item">
<h4 class="list-group-item-heading">
<a href="http://careers.steelseries.com/apply/3LXwyjYOrb/Customer-Experience-Specialist">
                                        Customer Experience Specialist                                    </a>
</h4>
<ul class="list-inline list-group-item-text">
<li><i class="fa fa-map-marker"></i>Chicago, IL</li>
<li><i class="fa fa-sitemap"></i>Operations</li>
</ul>

我希望它打印出来的是

Customer Experience Specialist
Chicago, IL
Operations
--------------

我试过的代码是这样的:

section = soup.find_all('div', class_='col col-xs-7 jobs-list')
for elem in section:
    wrappers = elem.find('ul').get_text()
    print(wrappers)

但是这样做是用太多的新行和空格为我打印它:

                                        Customer Experience Specialist                                    


Chicago, IL
Operations

请记住,职位上方还有 4 个空行,“操作”之后还有一个新行

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    试试这个:

    sections = soup.find_all('div', class_='col col-xs-7 jobs-list')
    sections = [section for section in sections.split("\n") if section and section != " "]
    print("\n".join(sections))
    

    问候!

    【讨论】:

    • 不幸的是,这似乎不起作用。我得到了同样的东西
    • 你能print(sections) 不加入吗,下一次尝试将是那个;)
    • 我现在知道了 ['\n\n\n\n Customer Experience Specialist \n\n\nChicago, IL\nOperations\n\n\n\n\n\n],但在 Customer、Chicago 和 Operations 的最后一个 \n 和第一个字母之间有很多空格
    • 已修改!再试一次^^
    • 我想通了!非常感谢您的帮助!发生的事情是我需要一个额外的 for 循环来划分每个列表,然后从那里我能够使用 strip() 函数。所以现在看起来像这样section = soup.find_all('div', class_='col col-xs-7 jobs-list') for elem in section: wrappers = elem.find('ul') for x in wrappers: text = wrappers.find('li').get_text() print(text.strip()) print("---")
    【解决方案2】:

    在 get_text() 函数之后添加 rstrip() 以删除所有尾随换行符。这将删除所有尾随空格,而不仅仅是单个换行符。

    否则,如果字符串 S 中只有一行,则使用 S.splitlines()[0]。

    【讨论】:

    • 第一种使用 rstrip() 的方法没有改变任何东西,而第二种方法导致它没有打印出任何东西
    猜你喜欢
    • 2021-05-05
    • 2021-10-22
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多