我正在尝试使用BeautifulSoup解析来自google.com/patents的声明,并将其放入DOCX表中。
我已经设法检索了声明,但是不幸的是,父div标签具有声明的第一部分,而子div-s是声明的其余部分的一部分,如下图所示。
当我运行程序时,表中的第一个单元格具有父级和所有子级div文本,并且div子级传播以下表单元格。
我想用父div的文本传播DOCX表中的第一个单元格,同时不包括子div传播,接下来的单元格用子div-s文本传播。
我尝试.decompose要求获得父母,我试图弄清楚如何重命名要放入表中的孩子。
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')
我希望能够将在父级中找到的声明开头的文本与声明一起解析到DOCX表的单元格1中,并从该单元格中排除子级。孩子们应该分别进入自己的牢房。
我还无法弄清楚如何将文本与父母和孩子分开。
为了避免重复,只需从顶部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')
此方法仅存储独立声明。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句