Narzard Narzard - 1 month ago 17
C# Question

Xpath with HTML AgilityPack

I am using HTMLAgilityPack to scrape some data from the web. I am right clicking the element in the page and then choosing "copy as Xpath" to get my path correct. For some reason, the following string is throwing an error and I am not sure what the issue is. I am scraping the 52 week high and low element.

Site: http://www.nasdaq.com/symbol/aapl

Code:

string yearHighLow = doc.DocumentNode.SelectNodes("//*[@id=\"quotes_content_left_InfoQuotesResults\"]/tbody/tr/td/div[1]/table/tbody/tr[7]/td[2]/text()")[0].InnerText;


Thanks

Answer

This is not a very good xpath, not flexible enough.Usually generated xpath's are bad.

If 52 week is a standard value you can use something like:

//td[./a[@id='52_week_high_low']]/following-sibling::td

or

//a[@id='52_week_high_low']/../following-sibling::td

This will select the element that contains the value for 52 week.