How to follow a link in QWebKit?

这一生的挚爱 提交于 2020-01-11 02:34:23

问题


Having a DOM of the following html;

<a href="?op=order">
<img class="img_button" src="picture.gif"
  onMouseOver="this.src='some.gif';"
  onMouseOut="this.src='some_other.gif';"
  alt="" border="0">
</a>

how to follow a link (href) in QWebKit (specifically QWebPage).

Please notice that it's an image that is linked.
I can't do it (and I don't want to even if I could) by simulating a mouse click as I don't use QWebView thus I don't have the page rendered.


回答1:


Assuming you have the link's QWebElement in a variable called "link" (located through findFirst or whatever):

link.evaluateJavaScript("var evObj = document.createEvent('MouseEvents');evObj.initEvent( 'click', true, true );this.dispatchEvent(evObj);")

(This is in Python, but it is the Javascript that matters. And yes, this is simulating a mouse click, but since it does not use coordinates, it works fine with an unrendered QWebPage.)




回答2:


Using DOM's click() Java Script function on the element makes the trick:

QWebPage * page = ...;
QWebElement el = page->mainFrame()->findFirstElement("a[href]");
el.evaluateJavaScript("this.click()"); 



回答3:


If you have QWebView and don't care about scrolling automatization, this may help:

const QWebElement &element=__your_element__;
QWebView *view =__your_view__;
QWebFrame *const frame=view->page()->mainFrame();
QPoint const elemPos=element.geometry().center();
frame->setScrollPosition(elemPos);
QPoint const scrollPos=frame->scrollPosition();

QMouseEvent * const impossibleMousePress = new QMouseEvent(QEvent::MouseButtonPress,elemPos-scrollPos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
QMouseEvent * const impossibleMouseRelease = new QMouseEvent(QEvent::MouseButtonRelease,elemPos-scrollPos,Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);
QApplication::postEvent(view,impossibleMousePress);
QApplication::postEvent(view,impossibleMouseRelease);


来源:https://stackoverflow.com/questions/1219880/how-to-follow-a-link-in-qwebkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!