gpt4 book ai didi

c# - WatiN 浏览器中的自定义 BeforeNavigate 事件

转载 作者:太空狗 更新时间:2023-10-29 23:51:05 24 4
gpt4 key购买 nike

我正在尝试使用 WatiN 更改用户代理字符串通过修改“导航前”事件中的标题来构建框架。我认为我真的很接近解决方案,但由于某种原因,在访问 url 大约一秒钟后,我被重定向到一个包含以下代码的空白页面。

如果我注释掉自定义的 BeforeNavigate-events,浏览器不会重定向到空白页面,这让我相信我的自定义事件需要稍作修改。您知道问题出在哪里吗?

要重现该问题,请下载 WatiN 并运行以下代码:

private SHDocVw.InternetExplorerClass _ieInstance;

private const string UserAgent =
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64)" +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153" +
"Safari/537.36\r\n";

bool _renavigating;
private IE _browser;

private void Form1_Load(object sender, EventArgs e)
{
_ieInstance = _ieInstance = new SHDocVw.InternetExplorerClass();
//_ieInstance.BeforeNavigate2 += BeforeNavigate;
_browser = new IE(_ieInstance);
_browser.GoTo("http://www.procato.com/my+headers/");
}

void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
headers += string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;
_ieInstance.Navigate((string)url,
(string)targetFrameName, (byte[])postData, (string)headers);
}
else
{
_renavigating = false;
}
}
}

@Noseratio 的建议也给了我一个空白页:

readonly SynchronizationContext _sc = SynchronizationContext.Current;

void BeforeNavigate(object pDisp, ref object url, ref object flags,
ref object targetFrameName, ref object postData, ref object headers,
ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!_renavigating)
{
var newHeaders = string.Format("User-Agent: {0}\r\n", UserAgent);
_renavigating = true;
cancel = true;

string thatUrl = (string)url;
object thatFlags = flags;
object thatTargetFrameName = targetFrameName;
object thatPostData = postData;
object thatHeaders = (headers != null && headers != Type.Missing &&
headers != System.DBNull.Value) ?
(headers.ToString() + newHeaders) : newHeaders;

_sc.Post(_ =>
{
((SHDocVw.IWebBrowser)pDisp).Navigate(
thatUrl,
ref thatFlags,
ref thatTargetFrameName,
ref thatPostData,
ref thatHeaders);
}, null);
}
else
{
_renavigating = false;
}
}
}

最佳答案

The request navigating to the page is enough.

在这种情况下,我建议您放弃 BeforeNavigate2,而只使用 _ieInstance.Navigate 进行导航,从而让您的生活更简单。例如:

private void Form1_Load(object sender, EventArgs e)
{
_ieInstance = _ieInstance = new SHDocVw.InternetExplorerClass();
_browser = new IE(_ieInstance);
_ieInstance.Navigate("http://www.procato.com/my+headers/", Headers: UserAgent);
}

procato 上显示的结果将是错误的 header ,因为加载页面会产生额外的请求,而这些请求不会有正确的 header 。但是,如果您使用像 Fiddler2 这样的工具,您会看到初始请求具有正确的用户代理 header 。

关于c# - WatiN 浏览器中的自定义 BeforeNavigate 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24242966/

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