gpt4 book ai didi

JavaScript:如何反对字符之间的推送字符串?

转载 作者:行者123 更新时间:2023-12-03 03:04:06 27 4
gpt4 key购买 nike

我正在尝试从如下所示的网站上抓取数据。它在一个 td 中有 4 行信息,我需要帮助抓取我希望最终结果在 JSON 文件中如下所示:

{
"mainTitle" : "Main Title"
"subTitle" : "Sub Title here"
"address1" : "Address Part One"
"address2" : "Address Part Two"
"postalCode" : "666666"
"telNo" : "12345678"
}

HTML:

<div class="contentpage">
<table>
<thead></thead>
<tbody>
<tr>Main Title</tr>
<tr>
<td>
<strong>Sub Title here</strong>
<br>
"Address Part One"
<br>
"Address Part Two"
<br>
"666666"
<br>
"Tel No: 12345678"
</td>
</tr>
</tbody>
</table>
</div>

到目前为止,我只能废弃主标题和副标题,我的 JavaScript:

function parseInfo ($) {
const result = {}
const enterRow = $('.contentpage > table').first().find('tr)

result.mainTitle = enterRow.eq(0).find('td').text().trim()
result.subTitle = enterRow.eq(1).find('td > strong').text().trim()

return result
}

最佳答案

您可以通过用换行符分割文本来获取这些值。

function parseInfo () {
const result = {};
const enterRow = $('.contentpage > table').first().find('tr');
result.mainTitle = enterRow.eq(0).text().trim();
result.subTitle = enterRow.eq(1).find('td > strong').text().trim();
let elements = enterRow.eq(1).find('td').text().trim().split('\n');
let filteredElements = elements.filter(val => val.replace(/\s/g, '').length).map(val => val.trim());
result.addressOne = filteredElements[1];
result.addressTwo = filteredElements[2];
result.addressCode = filteredElements[3];
result.telNumber = filteredElements[4];
return result;
}

我的 fiddle :https://jsfiddle.net/01zmmgy5/1/

关于JavaScript:如何反对字符之间的推送字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47247497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com