使用Python脚本

时间:2016-10-09 13:19:17

标签: python html beautifulsoup urllib bs4

我有一个小问题,我想在HTML文档中读取一个标题,到目前为止这是有效的,我得到了字符串的结果。我正在使用libraray bs4 BeautifulSoup和urllib.request。

HTML Code

您可以在第一张图片中看到HTML代码有差距,这个差距在命令行中甚至可见,但我只想要标题。 那么我如何删除输出中的HTML代码?

Command line Output

编辑: 这是您正在寻找的Python代码以及我使用过的

import urllib.request
from bs4 import BeautifulSoup
import codecs

htmlfile = urllib.request.urlopen("https://www.packtpub.com/packt/offers/free-learning")

htmltext = htmlfile.read()

print(htmltext)


soup = BeautifulSoup(htmltext, 'html.parser')

print(soup)

f = codecs.open("freebook.html", "w", "utf-8")
f.write(soup.get())

f.close()

我希望此代码可以帮助您

2 个答案:

答案 0 :(得分:0)

如果没有示例代码,很难为您提供准确的解决方案,但您可以使用h2.get_text(strip=true)其中h2是指向要打印出来的h2元素的变量。

这是关于get_text() - https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text

的文档

如果您需要更多帮助,请分享您的代码和html

答案 1 :(得分:0)

据我了解,您在变量中包含h2标记的文本内容,并且您想要删除空格。因此,您可以在bs4或strip=true中使用title = title.strip()