您好,我有一个关于在 HTML 中自动选择某些内容的问题。因此,如果我们仅将网页保存为 html,那么我们将获得 HTML 代码以及其他样式表和 javascript 代码。但是,我只想提取 <div class='post-content' itemprop='articleBody'>
之间的 HTML 代码。和 </div>
然后创建一个包含提取的 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 能做到吗?我可以生成一个新的干净的 html,它只包含 <div class='post-content' itemprop='articleBody'>
之间的内容吗?和 </div>
通过使用 javascript 或 Ruby?但是,至于如何编写实际代码,我没有头绪。
所以有人对此有任何想法吗?非常感谢!
最佳答案
我不太确定你在问什么,但我会尝试一下。
Can Ruby modify the DOM on a webpage?
简短的回答,没有。浏览器不知道如何运行 Ruby。他们确实知道如何运行 javascript,因此这通常用于实时 DOM 操作。
Can I generate a new clean 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 .
关于javascript - 如何自动选择html中的某些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166286/