Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BeautifulSoup get_text或findAll(text=True)时无法获取可见文本_Python_Html_Beautifulsoup - Fatal编程技术网

Python 使用BeautifulSoup get_text或findAll(text=True)时无法获取可见文本

Python 使用BeautifulSoup get_text或findAll(text=True)时无法获取可见文本,python,html,beautifulsoup,Python,Html,Beautifulsoup,我正在尝试使用bs4和python 3.4.1从网页中提取可见文本。为此,我将从我的汤中提取所有脚本和样式元素,然后继续从剩余的html中获取文本 出于测试目的,我使用x、y、z来观察汤的修改 html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read() soup = BeautifulSoup(html, "html5lib") #tried xml and h

我正在尝试使用bs4和python 3.4.1从网页中提取可见文本。为此,我将从我的汤中提取所有脚本和样式元素,然后继续从剩余的html中获取文本

出于测试目的,我使用x、y、z来观察汤的修改

html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read()
soup = BeautifulSoup(html, "html5lib") #tried xml and html.parser also
x = soup.prettify()
for elem in soup.find_all(['script', 'style']): #I know the text between <title></title> tags could not be interpreted as 'visible text' but thats's not the point of this example
    elem.extract()
y = soup.prettify()
z1 = soup.find_all(text=True)
z2 = soup.get_text()
z2是我试图实现的最简洁的版本,它让我获得了所有可见的文本,但在字符串的末尾仍然包含一个javascript的一些部分,比如:

/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'skilledupblog';
/* * * DON'T EDIT BELOW THIS LINE * * */
.... this continues with javascript

这不是一个孤立的案例,因为我在尝试使用的不同html页面上看到了类似的结果。

删除所有
脚本
样式
元素,然后获得
汤的文本对我来说很有效:

import urllib.request

from bs4 import BeautifulSoup

html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read()
soup = BeautifulSoup(html, "html5lib")

for elem in soup.find_all(['script', 'style']):
    elem.extract()

print(soup.get_text())

在打印文本中,没有您提到的
discus_shortname
脚本
元素的任何其他部分。

删除所有
脚本
样式
元素,然后让
的文本对我有效:

import urllib.request

from bs4 import BeautifulSoup

html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read()
soup = BeautifulSoup(html, "html5lib")

for elem in soup.find_all(['script', 'style']):
    elem.extract()

print(soup.get_text())

在打印文本中,没有您提到的
discus_shortname
脚本的任何其他部分。

在使用初始配置(bs4和python 3.4.1)时,我仍然得到了相同的结果,但通过使用python 2.7.8或python 35-32,我得到了清晰的预期HTML,没有任何脚本和/或样式标记。不确定原因是什么,但这是可行的。

我在使用初始配置(bs4和python 3.4.1)时仍然得到了相同的结果,但通过使用python 2.7.8或python 35-32,我得到了清晰的预期HTML,没有任何脚本和/或样式标记。不确定原因是什么,但这是有效的