简体   繁体   English

如何使用 JavaScript 从外部链接搜索 html 文件?

[英]How to search through an html file from an external link using JavaScript?

I'm very new to Javascript and coding in general and have a project I would really like to work on, but am having trouble knowing where to start, in particular step one.我对 Javascript 和一般编码非常陌生,并且有一个我真的很想从事的项目,但不知道从哪里开始,特别是第一步。 So far this is what I want the programme to do:到目前为止,这就是我希望程序执行的操作:

  1. Access/read html files from four external links (Is this where I use fetch()? Are there any packages you can recommend for this?)从四个外部链接访问/读取 html 文件(这是我使用 fetch() 的地方吗?您可以为此推荐任何软件包吗?)

  2. User inputs a list of names用户输入姓名列表

  3. Search html files for each item in list为列表中的每个项目搜索 html 文件

4a. 4a。 If there is a match, then output 'match' and which file the match was found如果有匹配,则 output 'match' 以及找到匹配的文件

4b. 4b。 If no match then output 'no match'如果不匹配,则 output '不匹配'

Is it more complex than just using HTML, CSS and JavaScript?它是否比仅使用 HTML、CSS 和 JavaScript 更复杂?

Thank you in advance!先感谢您!

You won't be able to get data from external url in browser due to CORS policy由于CORS 政策,您将无法在浏览器中从外部 url 获取数据

What you should do instead is create server-side solution and API for it.你应该做的是为它创建服务器端解决方案和 API。

Server side solution should request the external page HTML code, search for the word and send the result back to the browser.服务器端解决方案应请求外部页面 HTML 代码,搜索单词并将结果发送回浏览器。

The problem with implementing this in the browser is because of cross-origin issues.在浏览器中实现这一点的问题是由于跨域问题。 Essentially you aren't allowed to fetch() nor XMLHttpRequest() to other domains unless they specifically let you to.本质上,除非他们明确允许您这样做,否则您不允许 fetch() 或 XMLHttpRequest() 到其他域。 See the mdn docs here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS在此处查看 mdn 文档: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

You could implement this is Node.js which allows you to run js in a desktop environment.您可以使用 Node.js 来实现它,它允许您在桌面环境中运行 js。 If you were doing so, i recommend the following:如果您这样做,我建议您执行以下操作:

  • use node-fetch to do HTTP requests使用node-fetch做 HTTP 请求
  • use cheerio to parse the data使用cheerio解析数据

Best Regards, Kelvin最好的问候, 开尔文

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

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