【发布时间】:2018-07-21 01:42:06
【问题描述】:
我使用 IE 在 vba 中编写了一个脚本来解析网页中的一些链接。问题是链接在iframe 内。我以某种方式调整了我的代码,以便脚本首先在该iframe 中找到一个链接,然后导航到该新页面并从那里解析所需的内容。如果我这样做,那么我可以获得所有链接。
网页网址:weblink
成功的方法(工作之一):
Sub Get_Links()
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim elem As Object, post As Object
With IE
.Visible = True
.navigate "put here the above link"
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set elem = .document.getElementById("compInfo") #it is within iframe
.navigate elem.src
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set HTML = .document
End With
For Each post In HTML.getElementsByClassName("news")
With post.getElementsByTagName("a")
If .Length Then R = R + 1: Cells(R, 1) = .Item(0).href
End With
Next post
IE.Quit
End Sub
我看到很少有网站在iframe 中不存在此类链接,因此,我无法选择使用任何链接来追踪内容。
如果您通过跟踪链接查看以下方法,那么您会注意到我已经解析了来自Iframe 内的网页的内容。 Iframe 中没有这样的链接来导航到新网页以定位内容。所以,我改用了contentWindow.document,发现它完美无缺。
从另一个站点解析Iframe内容的工作代码链接:
contentWindow approach
但是,我的问题是:为什么我应该导航到一个新网页来收集链接,因为我可以在登录页面中看到内容?我尝试使用contentWindow.document,但它给了我访问被拒绝的错误。如何像上面那样使用contentWindow.document 使下面的代码工作?
我试过这样但它抛出拒绝访问错误:
Sub Get_Links()
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim frm As Object, post As Object
With IE
.Visible = True
.Navigate "put here the above link"
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set HTML = .document
End With
''the code breaks when it hits the following line "access denied error"
Set frm = HTML.getElementById("compInfo").contentWindow.document
For Each post In frm.getElementsByClassName("news")
With post.getElementsByTagName("a")
If .Length Then R = R + 1: Cells(R, 1) = .Item(0).href
End With
Next post
IE.Quit
End Sub
我附上了一张图片,让您知道我在寻找哪些链接(它们用铅笔标记)。
这些是在其中找到一个这样的链接(我想抓取)的元素:
<div class="news">
<span class="news-date_time"><img src="images/arrow.png" alt="">19 Jan 2018 00:01</span>
<a style="color:#5b5b5b;" href="/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17019039003&opt=9">ABB India Limited - Press Release</a>
</div>
我想抓取的那个页面的链接图片:
从创建此线程的第一天起,我就严格要求不要使用此 url http://hindubusiness.cmlinks.com/Companydetails.aspx?cocode=INE117A01022 来定位数据。我从这个main_page_link 请求了任何解决方案,而没有触及 iframe 中的链接。但是,每个人都在尝试提供我已经在我的帖子中展示的解决方案。那我悬赏是为了什么?
【问题讨论】:
-
为什么不直接将 XHR 设置为 URL
http://hindubusiness.cmlinks.com/Companydetails.aspx?cocode=INE117A01022并从响应中提取链接? -
在我完成了您在我的帖子中已经描述过的建议之后,我开始了这篇文章。我希望任何解决方案都无需使用 iframe 中可用的链接导航到新网页。由于所需的链接在第一页中可用,我想应该有任何方法可以在不导航到新页面的情况下获取这些链接。
-
我不建议你导航,我建议做XHR而不是使用IE。
-
@QHarr 我上面指出的链接中有一些示例,显示两个页面是否具有相同的来源。通常
<iframe>src URL 和包含页面 URL 应该具有相同的协议和主机。动态加载的内容不会影响政策。
标签: vba excel iframe web-scraping internet-explorer-11