【问题标题】:Preserve certain HTML tags when extracting with BeautifulSoup使用 BeautifulSoup 提取时保留某些 HTML 标签
【发布时间】:2018-09-06 06:11:42
【问题描述】:

我有以下 HTML:

<div class="description">Item 1<br>Item 2<br></div>

我使用 BeautifulSoup 获取description 类中的内容:

descriptionItems = container.find('div', attrs={'class': 'description'}).text.strip()

我得到的是Item 1Item 2

我如何获得Item 1&lt;br&gt;Item 2&lt;br&gt;,即div标签之间的内容,包括br标签?

【问题讨论】:

  • 单独descriptionItems = container.find('div', attrs={'class': 'description'}) 有效吗?
  • 确实如此,但我得到了完整的标签,没有任何内容被剥离:&lt;div class="description"&gt;Item 1&lt;br&gt;Item 2&lt;br&gt;&lt;/div&gt;,

标签: python beautifulsoup web-crawler screen-scraping extraction


【解决方案1】:

你可以用这个:

container = BeautifulSoup('<div class="description">Item 1<br>Item 2<br></div>', 'lxml')
desc_items = ''.join(str(x) for x in container.find('div', class_='description').contents)
print(desc_items)
# Item 1<br/>Item 2<br/>

说明:

.contents 为您提供标签所有内容的列表。

['Item 1', <br/>, 'Item 2', <br/>]

您只需使用''.join() 即可加入他们。但是,像&lt;br/&gt; 这样的标签类型是&lt;class 'bs4.element.Tag'&gt;,所以join 将引发TypeError 错误,因为它期望所有项目都是str 类型。因此,您必须先将其转换为 str

【讨论】:

  • 效果出奇的好。我什至不需要第一行。谢谢!
猜你喜欢
  • 2021-09-12
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 2014-12-01
相关资源
最近更新 更多