python lxml.html: 在 html 文档字符串中提取前面的文本

python lxml.html: pull preceding text in html docstring

我正在尝试根据 html 文档中它前面的文本来识别给定的 <table> 元素。

我目前的方法是将每个 html table 元素字符串化并在文件文本中搜索其文本索引:

filing_text=request.urlopen(url).read()

#some text cleanup here to make lxml's output match the .read() content
ref_text = lxml.html.tostring(filing_text).upper().\
              replace(b"&#160;",b"&NBSP;")
    tbl_count=0
    for tbl in self.filing_tree.iterfind('.//table'):
        text_ind=reftext.find(lxml.html.tostring(tbl).\
                              upper().replace(b"&#160;",b"&NBSP;"))
        start_text=lxml.html.tostring(tbl)[0:50]
        tbl_count+=1
        print ('tbl: %s; position: %s; %s'%(tbl_count,text_ind,start_text))

根据 table 元素的起始索引,我可以在前面的 x 个字符中搜索可能有助于识别 table 内容的文本。

此方法的两个问题:

  1. 由于标记密度(即标记文本与内容的比例)从 url 到 url 不等,因此很难在前面的文本中标准化我的搜索范围。 html 的 2500 个字符可能包含实际内容的 300 个字符或 2000
  2. 对每个 table 元素进行一次序列化和搜索似乎效率很低。它给网络抓取工作流程增加了比我想要的更多的开销

问题:有没有更好的方法?有没有lxml方法可以提取给定元素之前的文本内容?我在想象像 itertext() 这样的东西,它从元素向后移动,递归地通过 html 文档字符串。

用美汤。只是一个让你开始的片段:

>>> from bs4 import BeautifulSoup
>>> stupid_html = "<html><p> Hello </p><table> </table></html>"
>>> soup = BeautifulSoup(stupid_html )
>>> list_of_tables = soup.find_all("table")
>>> print( list_of_tables[0].previous )
 Hello