我正在编写GM脚本,以从包含一个表(其中只有1个表,并且没有ID)的网页上抓取信息,并将该表中的某些信息附加到现有网页中。除了从GM_xmlhttprequest
获得的文件中提取信息之外,我已经完成了所有工作。
GM_xmlhttpRequest({
method: 'GET',
url: tableToBeScrape,
onload: function (response) {
var respDoc = response.responseText;
console.log(respDoc);
alert(respDoc);
}
});
respDoc以完整的HTML格式返回网页。但是我很难提取信息。我尝试了几种方法
var listAllArray = [];
responseHTML = new DOMParser().parseFromString(response.responseText, 'text/html');
listAllArray = responseHTML.getElementsByClassName('table table-bordered table-striped table-condensed');
使用for循环并通过
listAllArray
循环,我从数组中什么都没得到。这是html的样子
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Part ID</th>
<th>Serial Number</th>
...
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
...
<td>123</td>
<td>sn123456</td>
...
<td>shelf 12</td>
</tr>
</tbody>
</table>
如何从表中提取零件ID,序列号和位置?
第2部分:
我从
response.responseText
获得的响应与我所假定的不同。没有表,而是div ul li
。<div class='search_refinements' data-collapsed='true' data-role='collapsible'>
<h4>Refine Your Results</h4>
<ul data-filter='true' data-role='listview'>
<li data-role='list-divider'>Company Name</li>
<li> ACB Inc. </li>
...
<li data-role='list-divider'>Part</li>
<li> 123 </li>
<li data-role='list-divider'>Serial Number</li>
<li> sn123456</li>
...
<li data-role='list-divider'>Location</li>
<li> shelf 12</li>
</ul>
</div>
最佳答案
假设您使用的是jQuery,
你可以这样做,
var table = $(response.responseText).find("table").find("tbody");
var rows = table.find('tr');
rows.each(function(index, row){
var columns = $(row).find('td');
var partId = columns.eq(0).html();
var serialNumber = columns.eq(1).html();
var location = columns.eq(2).html();
console.log("Part Id : " + partId);
console.log("Serial Number : " + serialNumber);
console.log("Location : " + location);
});