简体   繁体   English

从DOM解析HTML

[英]Parsing HTML from DOM

I'm trying to parse the alt text from the following HTML code, that I got from the Xpath denoted as "FIRST_RECORD_LINK". 我正在尝试从以下HTML代码中解析alt文本,该文本是从Xpath中以“ FIRST_RECORD_LINK”表示的。

 <img data-aria-label-part="" src="https://pbs.twimg.com/media/Dc10VX_UwAAJxPM.jpg" alt="Millenials are more likely than Baby Boomers to be living with a disability. Provided by the Center for Talent Innovation Disability Inclusion Report."> 

My javascript code looks like this: 我的JavaScript代码如下所示:

 var FIRST_RECORD_LINK = '//*[@id="stream-item-tweet-999772032685527042"]/div[1]/div[2]/div[3]/div/div/div/div/img'; var FIRST_RECORD = document.evaluate(FIRST_RECORD_LINK, document, null, XPathResult.ANY_TYPE, null).iterateNext(); console.log(FIRST_RECORD); var parser = new DOMParser(); var xmlDoc = parser.parseFromString(FIRST_RECORD,"text/html"); console.log(xmlDoc.getElementsByTagName("img")[0].childNodes[0].getAttribute("alt")); 

What am I doing wrong? 我究竟做错了什么? I apologize in advance for not using the code boxes, i'm visually impaired and they're not working with my screen reader. 对于未使用代码框,我事先表示歉意,我有视觉障碍,他们无法与我的屏幕阅读器配合使用。

Once you have obtained the img in FIRST_RECORD by evaluating the xpath, you can read the alt attribute with getAttribute : 通过评估xpath获得FIRST_RECORDimg之后,您可以使用getAttribute读取alt属性:

FIRST_RECORD.getAttribute('alt');

See a working example (with an updated xpath so it works in stackoverflow): 查看一个工作示例(具有更新的xpath,使其可以在stackoverflow中使用):

 // The following path was modified to work in stackoverflow var FIRST_RECORD_LINK = '//img'; var FIRST_RECORD = document.evaluate(FIRST_RECORD_LINK, document, null, XPathResult.ANY_TYPE, null).iterateNext(); console.log(FIRST_RECORD); console.log(FIRST_RECORD.getAttribute('alt')); 
 <img data-aria-label-part="" src="https://pbs.twimg.com/media/Dc10VX_UwAAJxPM.jpg" alt="Millenials are more likely than Baby Boomers to be living with a disability. Provided by the Center for Talent Innovation Disability Inclusion Report."> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM