Python - 从报纸网站获取文本

时间:2017-06-09 07:03:58

标签: html python-2.7

我开了一个宠物项目: 从报纸网站获取“英文文本”并将其转储到文件中。 通过我的研究,我被介绍了有趣的模块,如bs4,re等 我当前的脚本使用bs4。脚本语言:Python(2.7)。请看看。

from bs4 import BeautifulSoup
import urllib2

from_the_web = urllib2.urlopen("http://www.thehindu.com/todays-paper/tp-national/") #This is a file-object
soup = BeautifulSoup(from_the_web.read(),'html.parser')

myFile = open('Nag.txt','w')
myFile.truncate()
myFile.write("These are the results from thehindu.com:\n\n")

failures = 0
for line in soup.get_text():
    try:
        myFile.write(line)
    except:
        failures += 1

print "Successfully written lines with %d failures" %(failures)
myFile.close()

print "Done"

我已经能够提取所有文本,但是,很多非英文文本也被转储到我的文件(Nag.txt)中。这是一个示例:

(function (w, d, u) {
w.readyQ = [];
w.bindReadyQ = [];
function p(x, y) {
if (x == "ready") {
w.bindReadyQ.push(y);
} else {
w.readyQ.push(x);
}
};
var a = {ready: p, bind: p};
w.$ = w.jQuery = function (f) {
if (f === d || f === u) {
return a
} else {
p(f)
}
}
})(window, document)

这是其他一些与HTML结合的脚本语言吗?如果是这样,请提供有关如何从网站获取纯英文文本的建议。

1 个答案:

答案 0 :(得分:0)

您需要使用BeautifulSoup过滤掉<script>标记。例如,

soup.find_all("div")
相关问题