这是我第一次使用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
任何帮助都是非常感谢的,男孩和女孩!!!在
也许还有一种更优雅的方法,但是我用来查找元素所在的页面是.interncestors('LTPage')。下面的示例代码将找到“My Text”的所有实例,并告诉您它位于哪个页面:
我希望这有帮助!:)
相关问题 更多 >
编程相关推荐