如何使用 BeautifulSoup 从 parent 和 children 标签中获取文本以放入 DOCX table

How to use BeautifulSoup to get text from parent and children tags to put into a DOCX table

我正在尝试使用 BeautifulSoup 解析来自 google.com/patents 的声明并将它们放入 DOCX table.

我已经设法检索到声明,但不幸的是 parent div 标签包含声明的第一部分,而 children div-s 是声明的一部分索赔的其余部分如下图所示。

当我 运行 程序时,table 中的第一个单元格包含 parent 和所有 children div 文本,并且div children 传播以下 table 个细胞。

我想使用 Parent div 中的文本传播 DOCX table 中的第一个单元格,同时排除 children div,以及以下带有来自 children div-s.

文本的单元格

我已经尝试分解声明以获得 parent, 我已经尝试弄清楚如何重命名 children 以放入 table。

   from bs4 import BeautifulSoup
   import requests
   from docx import Document
   from docx.enum.table import WD_TABLE_DIRECTION

   document = Document()

   url = 'https://patents.google.com/patent/US7054130?oq=US7654309'

   response = requests.get(url)
   data = response.text
   soup = BeautifulSoup(data, 'html.parser')

   claims = soup.select('div .claim-text')

   table = document.add_table(rows=1, cols=2, style='Table Grid')

   for claim in claims:

        if not claim.find('claim-ref'):

            try:
                print(claim.text + '\n')
                cells = table.add_row().cells
                cells[0].text = claim.text

                # Add space between paragraphs
                document.add_paragraph('')

            except:

                continue

    document.save('my_test.docx')

我希望能够将 parent 中声明开头的文本解析为 DOCX table 的单元格 1,并排除 children从细胞。 children 应该分别进入它们自己的单元格。

这是我尝试 运行 程序时得到的结果:

这就是我想要实现的目标:

我一直无法弄清楚如何将文本与 parent 和 children 分开。

为避免重复,只需从顶部获取整个文本 div 并适当拆分,例如:

from bs4 import BeautifulSoup
import requests
from docx import Document

document = Document()
url = 'https://patents.google.com/patent/US7054130?oq=US7654309'
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data, 'html.parser')
claims_section = soup.find('section', itemprop='claims').div.div
table = document.add_table(rows=0, cols=2, style='Table Grid')

for div in claims_section.find_all('div', class_='claim', recursive=False):
    div_claim_text = div.find_next('div', class_='claim-text')
    lines = [line.strip() for line in div_claim_text.text.splitlines() if line.strip()]

    for line in lines:
        cells = table.add_row().cells
        cells[0].text = line

document.save('my_test.docx')

此方法仅存储独立声明。

您可以从父 div 获取文本,然后从子 div 获取文本,然后将数据追加到为此目的创建的新列表中。

//div/text[1] 允许从 div

中获取第一个文本

[e for e in _list if e] 允许删除空元素

试试这个:

from lxml import html
import requests
from docx import Document
from docx.enum.table import WD_TABLE_DIRECTION

document = Document()

url = 'https://patents.google.com/patent/US7054130?oq=US7654309'

response = requests.get(url)
data = response.text
doc = html.fromstring(data)

parent_claim = [e.strip() for e in doc.xpath("//div[@id='CLM-00001']/div[@class='claim-text']/text()[1]") if e.strip()]
children_claims = [e.strip() for e in doc.xpath("//div[@id='CLM-00001']/div[@class='claim-text']/div[@class='claim-text']/text()") if e.strip()]
table = document.add_table(rows=1, cols=2, style='Table Grid')
claims = []
for e in parent_claim:
    claims.append(e)
for e in children_claims:
    claims.append(e)

for claim in claims:

        print(claim + '\n')
        cells = table.add_row().cells
        cells[0].text = claim

        # Add space between paragraphs
        document.add_paragraph('')

document.save('my_test.docx')

输出:

我以为我找到了解决办法;但是在现实生活中应用代码证明代码是错误的。

嵌套的 div 导致 table 中出现重复条目​​。我尝试使用分解函数来解决问题,但如果声明具有多层嵌套的 div 标签,它就会失败。

from bs4 import BeautifulSoup
import requests
from docx import Document
from docx.enum.table import WD_TABLE_DIRECTION

document = Document()
url = 'https://patents.google.com/patent/US7054130?oq=US7654309'
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data, 'html.parser')
#claims = soup.select('div .claim-text')
claims =soup.find_all("div", class_="claim-text")




for claim in claims:

    table = document.add_table(rows=0, cols=2, style='Table Grid')
    if claim.find('claim-ref'):
        continue

    else:
        try:
            claim.find('div').decompose()
        except:
            continue
        for row in claim.parent.text.split('\n'):
            if row == '':
                continue
            else:
                cells = table.add_row().cells
                cells[0].text = row
                print(row)
            # Add space between tables
    document.add_paragraph('')

再次感谢!