如何使用带有VBA的Selenium从PDF抓取特定文本

时间:2019-06-18 11:44:01

标签: excel vba selenium web-scraping

我正在做一个自动化项目,该项目从打开浏览器,访问URL,登录到它,单击几个链接,最后单击一个可以在浏览器本身中打开PDF文件的链接开始。现在,我想要从PDF到Excel的一行(如字符串)。

我使用了以下代码,这是GitHub的作者提供的。使用该代码,我只能抓取PDF的第一行。我使用的PDF是动态的,有时我需要的信息在第5行,有时在第25行,依此类推...

希望我已经解释了,如有任何错误,请原谅我。

Private Sub Handle_PDF_Chrome()
Dim driver As New ChromeDriver
driver.Get "http://static.mozilla.com/moco/en-US/pdf/mozilla_privacypolicy.pdf"

' Return the first line using the pugin API (asynchronous).
Const JS_READ_PDF_FIRST_LINE_CHROME As String = _
"addEventListener('message',function(e){" & _
" if(e.data.type=='getSelectedTextReply'){" & _
"  var txt=e.data.selectedText;" & _
"  callback(txt && txt.match(/^.+$/m)[0]);" & _
" }" & _
"});" & _
"plugin.postMessage({type:'initialize'},'*');" & _
"plugin.postMessage({type:'selectAll'},'*');" & _
"plugin.postMessage({type:'getSelectedText'},'*');"

' Assert the first line
Dim firstline
firstline = driver.ExecuteAsyncScript(JS_READ_PDF_FIRST_LINE_CHROME)
Assert.Equals "Websites Privacy Policy", firstline

driver.Quit
End Sub

1 个答案:

答案 0 :(得分:2)

假设您的代码确实起作用,则需要更改正则表达式和索引。

regex变为

[^\r\n]+

检索所有行(忽略空行)。然后,用4进行索引以获得第5行。

正则表达式说明:

enter image description here

addEventListener('message',function(e){if(e.data.type=='getSelectedTextReply'){var txt=e.data.selectedText;
callback(txt && txt.match(/[^\r\n]+/g)[4]);}});
plugin.postMessage({type:'initialize'},'*');
plugin.postMessage({type:'selectAll'},'*');
plugin.postMessage({type:'getSelectedText'},'*');