admin管理员组

文章数量:1278886

I have a web page with some data that I want to extract So I open Chrome Developpers Console and type:

$x('//a[contains(@class, "link-class")]/text()')

but I've got:

[text, text, text]

instead of list of strings. Is there any to get list of strins that I can copy to my notepad, excel etc?

I have a web page with some data that I want to extract So I open Chrome Developpers Console and type:

$x('//a[contains(@class, "link-class")]/text()')

but I've got:

[text, text, text]

instead of list of strings. Is there any to get list of strins that I can copy to my notepad, excel etc?

Share Improve this question asked Sep 8, 2017 at 15:47 GhostKU GhostKU 2,1088 gold badges25 silver badges36 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Within the console you can actually just type copy('some data') and it will copy to your clipboard. You will still have to format the information first.

Try this:

const formatted = JSON.stringify($x('//a[contains(@class, "link-class")]/text()').map((a) => a.data));

copy(formatted);

$x() returns DOM elements (in this case text nodes), so you need a step to extract the string from inside. You might have more luck with

$x('//a[contains(@class, "link-class")]').map( elt => elt.innerText );

if you have an array and want to pretty print it, you could simply do:

console.log(arr.join("\n"));

in your case then

console.log(
  $x('//a[contains(@class, "link-class")]/text()')
    .map(el => el.innerText)
    .join("\n")
);

you could also format them like:

console.log(arr.map((el, ix) => ix + " : " + el.innerText).join("\n"));

to get:

0 : text1

1 : text2

You can use the Array.forEach(..) method to go through the DOM elements returned by $x() and log their data:

$x('//a[contains(@class, "link-class")]/text()').forEach((a) => console.log(a.data))

For a string of texts separated with \n use:

$x('//a[contains(@class, "link-class")]/text()').map((a) => a.data).join('\n')

本文标签: javascriptHow to copy some data from Chrome ConsoleStack Overflow