python - 是否可以在没有循环或附加模块的情况下从 BeautifulSoup 获取以下信息?

标签 python python-3.x beautifulsoup

我正在使用 BeautifulSoup4 和 Python 3。

我正在尝试抓取具有以下结构的网页的一部分:

<h1>Main Title Here<br/>

<small>
Subtitle Here - 
More Pieces of Subtitle Here</small>
</h1>

到目前为止,我已经尝试过:

  • 打印整个元素的文本 print(soup.find('h1').text) --打印时有多余的空间,使其难以操作。
  • 获取元素的内容 --这似乎产生了 结果与文本相同

因此,使用上述两种方法,我的输出如下所示:

Main Title Here multiple spaces here multiple spaces here Subtitle Here - multiple spaces here multiple spaces here More Pieces of Subtitle Here

它们都返回带有换行符和大量空格的文本。我已尝试以下方法来清理返回的数据:

  • 使用 Replace() 和 Strip()
    --这会稍微清理一下,但是,strip仅删除最外面的空格,而replace有可能删除所有空格 (我不想要)
  • 使用 Decompose() 和 Extract()
    --这删除了所有内容 "small"内标记并返回<none>标签。

我希望输出如下所示:
(第 1 行)这里的主要标题
(第 2 行)这里有字幕 - 这里有更多字幕

或者这也可以:
(1 行)这里是主标题,这里是副标题 - 这里是更多副标题

基本上,我需要将其压缩为一两行,没有多余的空格,并删除所有 html 标签。

根据我在此处其他地方读到的内容,我要么需要使用 for 循环来迭代页面的这一小部分(据我所知,这还需要将“Find”更改为“FindAll”,或者,我需要导入 re 模块。

是否有办法在不使用循环或导入模块的情况下实现我想要的结果?

以下是我尝试过的其他一些方法(几乎没有成功):

#Grabbing element, then next element separately
    print(soup.findAll('h1')[0].next)
    h=(soup.findAll('small')[0].next)
    h=h.replace('\n', '')
    print(h.strip())

#Grabbing by div and looping through
    i = soup.find('div', attrs={'page-header'})
    children = i.findChildren()
    for child in children:
         print(child)

最佳答案

我建议您依靠标题中的标签而不是换行符:

h1 = soup.find('h1')
list(h1.strings)[0] # The first string of the header
#'Main Title Here'
h1.find('small').string.strip() # The string in <small>
#'Subtitle Here - \nMore Pieces of Subtitle Here'

关于python - 是否可以在没有循环或附加模块的情况下从 BeautifulSoup 获取以下信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54757238/

相关文章:

python - BeautifulSoup: AttributeError: 'str' 对象没有属性 'copy' 。在 Ubuntu 上工作,在 Windows 上失败

python - BeautifulSoup - findAll 不在特定标签内

python - 如何避免Python中的if语句多次重复条件?

python - 在Python中从字典中删除一些固定数量的键的快速方法?

Python - 从其他类中的方法检索值

python - Openpyxl:迭代一列的所有行

python - 如何将 Django 设置导入 python 独立脚本

python - 除了计算之外,还可以使用现有数据框选择性地构建新数据框

python - 如何使用 BeautifulSoup 从所有脚本中提取正确的脚本

python - 从 <a> BeautifulSoup 中提取 href