这是我第一次使用PDFQuery抓取 PDF。
我需要做的是从多页价目表中获取价格,我想将产品代码提供给 PDFQuery,它应该找到代码并返回旁边的价格。问题是,使用 Github 页面上的第一个示例获取了文本的位置,但它清楚地表明“请注意,我们不必知道名称在页面上的位置,或者它在哪个页面上”。我的价目表就是这种情况,但所有其他示例都指定了页码 ( LTPage[pageid=1]
),但我不知道从哪里获取页码。
如果我不指定页码,它将返回所有页面同一位置的所有文本。
此外,我还添加了 exactText
函数,因为代码可能是“92005”、“92005C”、“92005G”,因此单独使用 :contains
没有多大帮助。
我尝试过选择元素所在的页面,并使用 JQuery .closest
,但都没有成功。
我检查了PDFMiner documentation和 PyQuery documentation但我没有看到任何对我有帮助的=(
我的代码现在看起来像这样:
import pdfquery
pdf = pdfquery.PDFQuery("tests/samples/priceList.pdf")
pdf.load()
code = "92005G"
def exactText():
element = str(vars(this))
text = str("u'" + code + "\\n'")
if text in element:
return True
return False
#This should work if i could select the page where the element is located
#page = pdf.pq('LTPage:contains("'+code+'")')
#pageNum = page.attr('pageid')
#Here I would replace the "8" with the page number i get, or remove the LTPage
#selector all together if i need to find the element first and then the page
label = pdf.pq('LTPage[page_index="8"] LTTextLineHorizontal:contains("'+code+'")').filter(exactText)
#Since we could use "JQuery selectors" i tried using ".closest", but it returns nothing
#page = label.closest('LTPage')
#pageNum = page.attr('pageid')
left_corner = float(label.attr('x0'))
bottom_corner = float(label.attr('y0'))
#Here I would replace the "8" with the page number i get
price = pdf.pq('LTPage[page_index="8"] LTTextLineHorizontal:in_bbox("%s, %s, %s, %s")' % (left_corner+110, bottom_corner, left_corner+140, bottom_corner+20)).text()
print price
非常感谢任何帮助,伙计们,女孩们!!!
最佳答案
可能有更优雅的方法,但我用来查找元素所在页面的是.interancestors('LTPage')。下面的示例代码将查找“My Text”的所有实例并告诉您它位于哪个页面:
for pq in pdf.pq('LTTextLineHorizontal:contains("My Text")'):
page_pq = pq.iterancestors('LTPage').next() # Use just the first ancestor
print 'Found the text "%s" on page %s' % ( pq.layout.get_text(), page_pq.layout.pageid)
希望有帮助! :)
关于jquery - PDF查询 : get Page number where element is located,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091693/