您好我有一个关于自动选择HTML中某些内容的问题。因此,如果我们仅将网页保存为html ,那么我们将获得HTML代码以及其他样式表和JavaScript代码。但是,我只想在<div class='post-content' itemprop='articleBody'>
和</div>
之间提取HTML代码,然后创建一个包含提取的HTML代码的新HTML文件。有可能这样做吗?示例代码如下:
<html>
<script src='.....'>
</script>
<style>
...
</style>
<div class='header-outer'>
<div class='header-title'>
<div class='post-content' itemprop='articleBody'>
<p>content we want</p>
</div>
</div></div>
<div class='footer'>
</div>
</html>
在我打字的时候,我正在思考javascript,它似乎能够操纵HTML DOM元素.. Ruby是否能够做到这一点?我是否可以使用javascript或Ruby生成仅包含<div class='post-content' itemprop='articleBody'>
和</div>
之间内容的新干净html?但是,关于如何编写实际代码,我没有任何线索。
所以有人对此有任何想法吗?非常感谢你!
答案 0 :(得分:2)
我不太确定你在问什么,但是我会对它进行抨击。
Ruby可以修改网页上的DOM吗?
简短的回答,没有。浏览器不知道如何运行Ruby。他们确实知道如何运行javascript,因此通常用于实时DOM操作。
我可以生成一个新的干净的HTML
是?在一天结束时,HTML只是一个特定格式的字符串。如果您想从该页面下载源代码并查找<div class='post-content' itemprop='articleBody'>
标记中的所有内容,可以通过以下几种方式进行操作。最好的可能是nokogiri
gem,它是一个ruby HTML解析器。您将能够为其提供表示旧页面的字符串(来自文件或其他文件),并删除您想要的内容。这样做会是这样的:
require 'nokogiri'
page = Nokogiri::HTML(open("https://googleblog.blogspot.com"))
# finds the first child of the <div class="post-content"> element
text = page.css('.post-content')[0].text
我相信这会为您提供您正在寻找的文字。可以找到更详细的nokogiri说明here。
答案 1 :(得分:0)
您想使用正则表达式。例如:
//The "m" means multi-line
var regEx = /<div class='post-content' itemprop='articleBody'>([\s\S]*?)<\/div>/m;
//The content (you'll put the javascript at the bottom
var bodyCode = document.body.innerHTML;
var match = bodyCode.match( regEx );
//Prints to the console
console.dir( match );
您可以在此处查看此操作:https://regex101.com/r/kJ5kW6/1