# 設置屬性的值
<div><h2>問題</h2>
<p>在你解析一個Document之后可能想修改其中的某些屬性值,然后再保存到磁盤或都輸出到前臺頁面。</p>
<h2>方法</h2>
<p>可以使用屬性設置方法 <code><a title="Set an attribute value on this element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#attr%28java.lang.String,%20java.lang.String%29">Element.attr(String
key, String value)</a></code>, 和 <code><a title="Set an attribute on all matched elements." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html#attr%28java.lang.String,%20java.lang.String%29">Elements.attr(String
key, String value)</a></code>.</p>
<p>假如你需要修改一個元素的 <code>class</code> 屬性,可以使用
<code><a title="Add a class name to this element's class attribute." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#addClass%28java.lang.String%29">Element.addClass(String
className)</a></code> 和 <code><a title="Remove a class name from this element's class attribute." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#removeClass%28java.lang.String%29">Element.removeClass(String
className)</a></code> 方法。</p>
<p><code><a title="A list of Elements, with methods that act on every element in the list." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html">Elements</a></code>
提供了批量操作元素屬性和class的方法,比如:要為div中的每一個a元素都添加一個
<code>rel="nofollow"</code> 可以使用如下方法:</p>
<pre><code>doc.select("div.comments a").attr("rel", "nofollow");
</code></pre>
<h2>說明</h2>
<p>與<code><a title="A HTML element consists of a tag name, attributes, and child nodes (including text nodes and other elements)." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html">Element</a></code>中的其它方法一樣,<code>attr</code> 方法也是返回當 <code><a title="A HTML element consists of a tag name, attributes, and child nodes (including text nodes and other elements)." href="http://jsoup.org/apidocs/org/jsoup/nodes/Element.html">Element</a></code>
(或在使用選擇器是返回 <code><a title="A list of Elements, with methods that act on every element in the list." href="http://jsoup.org/apidocs/org/jsoup/select/Elements.html">Elements</a></code>
集合)。這樣能夠很方便使用方法連用的書寫方式。比如:</p>
<pre><code>doc.select("div.masthead").attr("title", "jsoup").addClass("round-box");
</code></pre><br></div>
- Introduction
- 爬蟲相關技能介紹
- 爬蟲簡單介紹
- 爬蟲涉及到的知識點
- 爬蟲用途
- 爬蟲流程介紹
- 需求描述
- Http請求處理
- http基礎知識介紹
- http狀態碼
- httpheader
- java原生態處理http
- URL類
- 獲取URL請求狀態
- 模擬Http請求
- apache httpclient
- Httpclient1
- httpclient2
- httpclient3
- httpclient4
- httpclient5
- httpclient6
- okhttp
- OKhttp使用教程
- 技術使用
- java執行javascript
- 網頁解析
- Xpath介紹
- HtmlCleaner
- HtmlCleaner介紹
- HtmlCleaner使用
- HtmlParser
- HtmlParser介紹
- Jsoup
- 解析和遍歷一個HTML文檔
- 解析一個HTML字符串
- 解析一個body片斷
- 從一個URL加載一個Document
- 從一個文件加載一個文檔
- 使用DOM方法來遍歷一個文檔
- 使用選擇器語法來查找元素
- 從元素抽取屬性,文本和HTML
- 處理URLs
- 示例程序 獲取所有鏈接
- 設置屬性的值
- 設置一個元素的HTML內容
- 消除不受信任的HTML (來防止XSS攻擊)
- 正則表達式
- elasticsearch筆記
- 下載安裝elasticsearch
- 檢查es服務健康