【发布时间】:2016-05-14 15:09:25
【问题描述】:
我正在尝试使用 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()
我看到 x 是未更改的 HTML,y 是没有脚本和样式标签的相同 HTML,这是正确的。
z1 返回一个 ResultSet,它仍然包含一些 html 标签,例如 <div class="category" id="article_top_name"></div> AND 还有
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'skilledupblog';
/* * * DON'T EDIT BELOW THIS LINE * * */
.... this continues with javascript
z2 是我想要完成的最简洁的版本,它为我提供了所有可见的文本,但在字符串的末尾仍然包含一个 javascript 的部分,比如这个:
/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'skilledupblog';
/* * * DON'T EDIT BELOW THIS LINE * * */
.... this continues with javascript
这不是一个孤立的案例,因为我在尝试使用的不同 html 页面上看到了类似的结果。
【问题讨论】:
标签: python html beautifulsoup