如何在使用Beaufifulsoup进行解析时用共享相同ID的另一个内容替换ID标记

2024-06-01 01:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用beautifulsoup4解析数千个html页面。我很难找到每个ID的内容并替换它。我上传的示例将帮助您理解我遇到的问题

我拥有的html页面的一个简单示例是

<derivativeHolding>
    <securityTitle>
        <value>Performance Shares</value>
    </securityTitle>
    <conversionOrExercisePrice>
        <footnoteId id="F3"/>
    </conversionOrExercisePrice>
</derivativeHolding>


<derivativeHolding>
    <securityTitle>
        <value>Stock Option (Right to Buy)</value>
    </securityTitle>
    <conversionOrExercisePrice>
        <value>35.57</value>
    </conversionOrExercisePrice>
</derivativeHolding>

<footnotes>
    <footnote id="F3">contents</footnote>
</footnotes>

我想替换“footnoteId^{id1}”$

我不知道如何更换零件,所以我没有准备代码

我希望csv文件中的结果是这样的

enter image description here

其中第一行是变量名列表


Tags: id示例内容valuehtml页面beautifulsoup4f3
1条回答
网友
1楼 · 发布于 2024-06-01 01:16:40

示例解决方案仅显示了查找脚注(如果脚注被引用)的方法:

from bs4 import BeautifulSoup

r = open('test.html', 'r')
content = r.read()
r.close()
soup = BeautifulSoup(content, 'lxml')

results = []

holdings = soup.find_all('derivativeholding')
for holding in holdings:
    securityTitle = holding.securitytitle.value
    if securityTitle is None:
        continue  # no title?
    price = holding.conversionorexerciseprice.value
    if price is None:
        # check whether there's a footnote reference
        footnoteid = holding.conversionorexerciseprice.footnoteid
        if footnoteid is None:
            continue  # no price or footnote?
        price = soup.footnotes.find('footnote', {'id': footnoteid['id']})

    # join contents incase of empty list or multiple elements
    results.append(str("".join(securityTitle.contents)) + ',' + str("".join(price.contents)))

with open('output.csv', 'w+') as w:
    w.write('securityTitle,conversionOrExercisePrice\n')
    w.write("\n".join(results))

如果html结构稍有变化,则很可能需要对此进行微调,以避免在数千个页面中的许多页面上出现中断

相关问题 更多 >