繁体   English   中英

PDFQuery:获取元素所在的页码

[英]PDFQuery: get Page number where element is located

这是我第一次使用PDFQuery来抓取 PDF。

我需要做的是从包含几页的价目表中获取价格,我想将产品代码提供给 PDFQuery,它应该找到代码并返回旁边的价格。 问题是使用 Github 页面上的第一个示例获取文本的位置,但它清楚地表明“请注意,我们不必知道名称在页面上的位置,或者它在哪个页面上”。 我的价目表就是这种情况,但是所有其他示例都指定了页码( LTPage[pageid=1] ),但我没有看到我们从哪里获得页码。

如果我不指定页码,它会返回所有页面相同位置的所有文本。

此外,我添加了一个exactText函数,因为代码可能是,例如,“92005”、“92005C”、“92005G”,所以单独使用:contains并没有多大帮助。

我试过选择元素所在的页面,并使用 JQuery .closest ,两者都没有运气。

我检查了PDFMiner 文档PyQuery 文档,但没有看到任何对我有帮助的东西 =(

我的代码现在看起来像这样:

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')。 下面的示例代码将找到“我的文本”的所有实例并告诉您它在哪个页面上:

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)

我希望这有帮助! :)

这应该在 python3 中工作(注意调用 next(iterator) 来获取第一个页面祖先):

code = "92005G"

label = pdf.pq('LTPage:contains("{}")'.format(code))
page_pq = next(label.iterancestors('LTPage'))
pageNum = int(page_pq.layout.pageid)

label = pdf.pq('LTPage[page_index="{0}"] LTTextLineHorizontal:contains("{1}")'.format(pageNum, code)).filter(exactText)

left_corner = float(label.attr('x0'))
bottom_corner = float(label.attr('y0'))

price = pdf.pq('LTPage[page_index="{0}"] LTTextLineHorizontal:in_bbox("{1}, {2}, {3}, {4}")'.format(pageNum, left_corner+110, bottom_corner, left_corner+140, bottom_corner+20)).text()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM