相关疑难解决方法(0)

我可以使用BeautifulSoup删除脚本标签吗?

可以使用BeautifulSoup从HTML中删除脚本标记及其所有内容,还是必须使用正则表达式或其他内容?

html python beautifulsoup

84
推荐指数
3
解决办法
8万
查看次数

BeautifulSoup get_text不会删除所有标记和JavaScript

我正在尝试使用BeautifulSoup从网页获取文本.

下面是我写的脚本.它需要两个参数,第一个是输入HTML或XML文件,第二个是输出文件.

import sys
from bs4 import BeautifulSoup

def stripTags(s): return BeautifulSoup(s).get_text()

def stripTagsFromFile(inFile, outFile):
    open(outFile, 'w').write(stripTags(open(inFile).read()).encode("utf-8"))

def main(argv):
    if len(sys.argv) <> 3:
        print 'Usage:\t\t', sys.argv[0], 'input.html output.txt'
        return 1
    stripTagsFromFile(sys.argv[1], sys.argv[2])
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))
Run Code Online (Sandbox Code Playgroud)

不幸的是,对于许多网页,例如:http://www.greatjobsinteaching.co.uk/career/134112/Education-Manager-Location 我得到这样的东西(我只展示了几个第一行):

html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    Education Manager  Job In London With  Caleeda | Great Jobs In Teaching

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-15255540-21']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
Run Code Online (Sandbox Code Playgroud)

我的剧本有什么问题吗?我试图将'xml'作为第二个参数传递给BeautifulSoup的构造函数,以及'html5lib'和'lxml',但它没有帮助.是否有一个替代BeautifulSoup可以更好地完成这项任务?我想要的只是提取将在此网页的浏览器中呈现的文本.

任何帮助都感激不尽.

html python xml screen-scraping beautifulsoup

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

beautifulsoup ×2

html ×2

python ×2

screen-scraping ×1

xml ×1