在python中从htm中提取标签不一致的文本

问题描述 投票:0回答:1

我需要摘录 SEC 文件的一部分。不幸的是,不同公司的归档方式不同,因此每个页面上的源代码都不同,而且看起来我无法通过标签提取数据。我正在尝试下面的代码,但我无法让它工作。有谁知道如何让它正确找到文本,以便我可以返回正确的字符串?目前它找不到字符串,因此根据 URL 返回所有内容或不返回任何内容。

我认为问题可能是格式中的空格阻碍了它在代码中找到关键字并带回正确的部分。不同的 URL 有不同的格式,返回不同的开始值和结束值,例如https://www.sec.gov/Archives/edgar/data/0000731766/000073176624000085/unh-20240221.htm

第 9.01 条也可能不会被跟随。因此,如果有人知道如何提取第 7.01 项之后的部分,那将会非常有帮助。

url = "https://www.sec.gov/Archives/edgar/data/789019/000119312524011295/d708866d8k.htm"

headers = {'User-Agent': '[email protected]'}

request2 = urllib.request.Request(url, headers=headers)

response2 = urllib.request.urlopen(request2)

html2 = response2.read()

soup2 = BeautifulSoup(html2, features="html.parser")

text2 = soup2.get_text()

start_index = text2.find("Item 7.01")

end_index = text2.find("Item 9.01")

result_string = text2[start_index:end_index]

print(text2)
print(start_index)
print(end_index)
print(result_string)

我尝试将 URL 更改为字符串、“字符串”、“字符串”以防有帮助,但没有效果。我不知道还能尝试什么。

python-3.x extract text-extraction
1个回答
0
投票

问题似乎是不间断空格,一种方法可能是替换它,因此它适合您的选择/您想要查找的字符串:

html2.replace(r' ', " ")

要仅提取后面的部分/内容,请检查其

next_siblings
并在下一个项目开始时按特定情况下的条件进行中断:

for e in soup.find(string=re.compile("Item 7.01.")).parent.next_siblings:
    if e.get_text(strip=True).startswith('Item'):
        break
    else:
        print(e.get_text(strip=True))
示例

这里使用了

requests
,但结果是一样的。

import requests, re

url = "https://www.sec.gov/Archives/edgar/data/789019/000119312524011295/d708866d8k.htm"

headers = {'User-Agent': 'some-agent'}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text.replace(r' ', " "))

for e in soup.find(string=re.compile("Item 7.01.")).parent.next_siblings:
    if e.get_text(strip=True).startswith('Item'):
        break
    else:
        print(e.get_text(strip=True))
输出
On January 19, 2024, the Company posted a blog regarding the incident. A copy of the blog is furnished as Exhibit 99.1 to this report.
In accordance with General Instruction B.2of Form 8-K, the informationin this Item 7.01 and Exhibit 99.1, shall not be deemed to be “filed” for purposes of Section 18 of the Securities Exchange Act of 1934, as amended (the “Exchange Act”), or otherwise subject to the liability of that section, and shall not be incorporated by reference into any registration statement or other document filed under the Securities Act of 1933, as amended, or the Exchange Act, except as shall be expressly set forth by specific reference in such filing.
© www.soinside.com 2019 - 2024. All rights reserved.