ZH
開始使用

術語表

擷取與自動化

XPath

用來定位 HTML 或 XML 文件各部分的查詢語言,是爬蟲指向頁面內資料的兩種方式中較強大的一種。

Once a page is fetched and parsed, extraction is the act of pointing: THAT price, THOSE titles, the link inside the third card. XPath is a language for pointing. An expression describes a path through the document tree, and evaluating it returns whichever elements, attributes or text the path reaches. The syntax reads like a filesystem with opinions: //product descends to every product element anywhere, div/span steps from parent to child, and square-bracket predicates filter what qualifies, as in //div[@class='price'] or //li[position() less than four].

Its reputation for power rests on the places the alternative cannot go. XPath matches on text content, finding the span that literally says Out of stock. It traverses upward and sideways, from the element you can identify to the parent or sibling you actually want, as in //span[text()='Total']/following-sibling::span. It counts, compares and combines conditions inside a single expression. Whole categories of extraction that are contortions in other tools are one line here.

失敗模式是你自己寫出來的脆弱性。瀏覽器開發者工具提供一個「複製 XPath」的便利功能,它會產生從文件根部開始的絕對路徑,每一步和索引都寫死了,這樣的路徑在路徑上任何地方的下一次版面調整時就會失效。手寫、錨定在穩定屬性上的相對表達式,能撐過讓絕對路徑粉碎的改版。這門手藝在於選擇有意義的錨點,例如 id、data 屬性、文字標籤。

它在哪裡執行和它說什麼一樣重要。在伺服器端,爬蟲所依賴的解析函式庫原生支援 XPath,爬行框架也把它列為一等的選擇器。在瀏覽器中,雖然也能執行,但工具偏好它的對手,自動化框架則兩者都接受。實務上的熟練是雙語的:日常用 CSS 選擇器語法,需要文字比對或往上走的就用 XPath,依每次擷取選擇。

一個誠實的提醒:在 JavaScript 渲染的頁面上,在元素存在之前,任何表達式都幫不上忙。XPath 查詢的是你解析的樹,如果資料在載入後才抵達,你解析的樹就只是骨架。精確地指向一個空舞台,仍然是什麼也沒指到。

常見問題

爬取時該用 XPath 還是 CSS 選擇器?

兩者都用,依工作選擇。CSS 語法比較簡潔,在例行情況下普遍受到支援,例如類別、id、屬性、巢狀。XPath 在 CSS 碰不到的地方發揮價值:依文字比對元素、從找到的元素往上走到父元素或往旁邊走到兄弟元素,以及在一個表達式中結合好幾個條件。兩者都熟練花不了多少力氣,卻能省掉一整類的變通做法。

為什麼我複製的 XPath 這麼快就壞掉?

因為瀏覽器開發者工具的「複製 XPath」會產生寫死步驟和索引的絕對路徑,它編入的是頁面目前的幾何結構。路徑上任何結構改變都會讓它失效。寫一個錨定在穩定屬性或文字標籤上的簡短相對表達式,就能產生一個撐得過那些整批刪除複製路徑的改版的選擇器。

XPath 能依文字選取元素嗎?

Yes, and it is the signature capability. Expressions can match exact text, as in //button[text()='Add to cart'], or containment via contains(), and then navigate from the matched element to whatever you actually need. CSS selectors in scraping libraries have no equivalent, which is why text-anchored extraction is the usual reason a scraper reaches for XPath.

XPath 在大量使用 JavaScript 的頁面上能用嗎?

它查詢的是你交給它的任何樹。如果頁面以空殼的形式抵達,在腳本執行後才填入內容,對抓取的 HTML 執行的表達式只會找到骨架。要不在無頭瀏覽器中渲染後再執行,或者更好的做法,檢查資料是否以 JSON 資料流或內嵌狀態的形式存在,讓你完全不必指向 DOM 就能讀取。

回到完整詞彙表。

HProxy.

定義只能帶你走到這裡。 執行 對比 真實目標.

住宅代理 每 GB US$ 0.23 起,隨用隨付,餘額永不過期。

HProxy