我正在尝试使用 C# 桌面应用程序填写网站表单,我使用以下表单作为示例 -
https://formsmarts.com/html-form-example
我写了以下代码-
private void button1_Click(object sender, EventArgs e)
{
// Initialize Chrome WebDriver
IWebDriver driver = new ChromeDriver();
// Navigate to the form URL
driver.Navigate().GoToUrl("https://formsmarts.com/html-form-example");
// Find input fields by their IDs and fill them with desired values
driver.FindElement(By.Id("u_HbM_4607")).SendKeys("John");
driver.FindElement(By.Id("u_HbM_338354")).SendKeys("Doe");
driver.FindElement(By.Id("u_HbM_4608")).SendKeys("[email protected]");
driver.FindElement(By.Id("u_HbM_338367")).SendKeys("Website Feedback");
driver.FindElement(By.Id("u_HbM_4609")).SendKeys("Everything Rocks!!!");
// Submit the form
//driver.FindElement(By.Id("u_CU_221828")).Click();
// Close the browser
//driver.Quit();
}
我遇到以下异常 -
OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element: {"method":"css selector","selector":"#u_HbM_4607"}
在
driver.FindElement(By.Id("u_HbM_4607")).SendKeys("John");
这是我复制 ID 字段的位置 -
<input name="u_k0J_4607" id="u_k0J_4607" type="text" value="" class=" u-full-width" placeholder="Your first name" aria-required="true">
从这里,重定向到页面,预填写表单字段 从下面的答案中我知道我们还可以发送 URL 参数来填充字段
Are you just testing with an aspx page, or is the online approval form an aspx page?
You can try adding URL parameters to a GET request instead of POST.
http://www.amazon.co.uk/exec/obidos/search-handle-form?field-keywords=Harry+Potter
但是我如何创建这个 URL 呢? 我研究并从这里找到了格式 - https://helpx.adobe.com/in/sign/adv-user/web-form/url-parameters.html
但是我如何找到这个URL的参数名称 - https://formsmarts.com/html-form-example
请注意,在对问题的持续编辑中,您如何不断更改
id
值。如果 id
值不断变化,那么它是由服务器动态生成的,并且不是可靠的选择器。
有多种方法可以选择页面上的元素。有些比其他更复杂。在这种特殊情况下,元素本身可能仍然具有足够独特的属性来被挑选出来。为了进行测试,我首先使用该
placeholder
值。页面上的其他输入不太可能共享相同的值。
类似这样的:
driver.FindElement(By.CssSelector("input[placeholder='Your first name']")).SendKeys("John");
值得重复我对上述问题所做的评论......
网站抓取是逆向工程的一种练习
你不能一直做出假设。检查 DOM 资源管理器中的页面,导航到该元素,您会发现它位于
iframe
内。这使得它成为 that 文档的一部分。
这看起来可能有帮助。我并不完全相信“等待”部分,如果有必要,当然不会等待超过一秒钟左右,但有时网站抓取就是这样。
理想情况下等待不会使用Thread.Sleep(1000)
,而是使用
await Task.Delay(1000)
,这将涉及使此按钮单击处理程序async
。这真的取决于你。更重要的是参考iframe
文档。例如:
var frame = driver.Instance.FindElement(By.CssSelector("iframe.fs_embed"));
driver.Instance.SwitchTo().Frame(frame);
driver.FindElement(By.CssSelector("input[placeholder='Your first name']")).SendKeys("John");
请注意,上面的大部分内容都是从其他在线资源拼凑而成的未经测试的代码。您可能需要对其进行一些调试和修补。但总体而言,您需要:
识别
iframe
iframe
的 URL,并首先将其用作网站抓取中的 URL。我不知道目标网站是否有任何阻碍其工作的因素。有时他们这样做,有时他们不这样做。网站抓取是逆向工程的一种练习。