python - 使用 Beautifulsoup 抓取时如何删除多个空行

标签 python beautifulsoup

我的代码输出多个空换行符。 我如何删除所有空白区域?

from bs4 import BeautifulSoup
import urllib.request
import re
url = input('enter url moish')
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page,'lxml')
all = soup.find_all('a', {'class' : re.compile('itemIncludes')})
for i in all:
          print(i.text)

代码输出:

Canon EOS 77D DSLR Camera (Body Only)



LP-E17 Lithium-Ion Battery Pack



LC-E17 Charger for LP-E17 Battery Pack

期望的输出:

Canon EOS 77D DSLR Camera (Body Only)
LP-E17 Lithium-Ion Battery Pack
LC-E17 Charger for LP-E17 Battery Pack

谢谢!

最佳答案

您可以在打印前删除空行:

items = [item.text for item in all if item.text.strip() != '']

关于python - 使用 Beautifulsoup 抓取时如何删除多个空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483772/

相关文章:

python - 用户输入并陷入 while 循环

python - BeautifulSoup爬虫解析

python - 使用beautifulsoup4根据 sibling 区分两个相同标签内容

python - 从 python 中的嵌套 URL 中抓取并解析表

python - BeautifulSoup:AttributeError: 'NavigableString'对象没有属性 'children'

python - 从 Matplotlib .pngs 创建动画

android - 在 Python 和 Kivy 中使用 buildozer 时出现错误 "Unable to find Compiler"

python - 为什么我的 ttk.Treeview 单击处理程序在 tree.focus() 上返回错误的项目?

python - 从 Python heapq 中检索最小值

python - BeautifulSoup 在 Django 中没有得到任何输出