700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python从文件中提取特定文本_使用Python从HTML文件中提取文本

python从文件中提取特定文本_使用Python从HTML文件中提取文本

时间:2019-10-28 17:23:17

相关推荐

python从文件中提取特定文本_使用Python从HTML文件中提取文本

我发现最好的一段代码用于提取文本,而不需要javascript或不需要的东西:import urllibfrom bs4 import BeautifulSoupurl = "http://news.bbc.co.uk/2/hi/health/2284783.stm"html = urllib.urlopen(url).read()soup = BeautifulSoup(html)# kill all script and style elementsfor script in soup(["script", "style"]):

script.extract() # rip it out# get texttext = soup.get_text()# break into lines and remove leading and trailing space on eachlines = (line.strip() for line in text.splitlines())# break multi-headlines into a line eachchunks = (phrase.strip() for line in lines for phrase in line.split(" "))# drop blank linestext = '\n'.join(chunk for chunk in chunks if chunk)print(text)

你只需先安装BeautifulSoup:pip install beautifulsoup4

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。