[英]How to extract text from file (with in script tag) using Python or beautifulsoup
[英]Python: Extract Text from Script Tag using XPath
我正在嘗試使用 xpath 訪問下面 html 中的文本。
我寫了這個語句response.xpath(//script/text())來提取標簽內的文本。 出於某種原因,我沒有看到數據預期文本。 誰能看到我做錯了什么?
Method: response.xpath(//script/text())
<script>
digitalData={
page:{
pageInfo:{
destinationURL:window.location.href,
error:'',
language:'en' ,
country:'US' ,
pageName:'tangelo2' ,
articlepubdate:'' ,
articleenddate:'' ,
pageTitle: 'Health Services Innovation Company',
pageOwner:'' ,
pageTemplate:'' ,
pageCampaign:'',
tags:'',
pageLastPublishDate:'2020-01-08T12:15:04.032-06:00',
pageLastPublishedBy :'admin',
pageLastModifiedDate:'2020-01-08T10:24:36.466-06:00',
pageLastModifiedBy :'katrina'
},
recEngine:{
title:'Home',
image:'',
description:''
},
category:{
siteName: window.location.hostname.replace("www.", "") ,
version:'3.0',
contentType: '',
contentTopic: '',
contentSegment: '',
contentInitiative: '',
contentProduct: '',
contentProductLine: '',
primaryCategory:'tangelo2'
}
},
event:{ }
};
</script>
您的響應對象似乎是來自某些http.request的響應。
所以要獲取腳本內容,需要的操作順序如下:
txt = Response.content
- 獲取此響應的內容(字符串)。root = etree.fromstring(txt)
- 解析這個字符串,得到元素樹。script = root.xpath('//script')[0].text
- 獲取腳本內容(更詳細的描述見下文)。 可能您還應該添加所需的命名空間。另請注意,您的代碼包含這樣一個缺陷,即您未能將路徑括在引號中(單引號或雙引號)。 但即使你這樣做了,結果也將是一個文本節點列表,只包含 1 個元素。
我的解決方案更簡單、更直觀,因為它:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.