我正在使用pdfminer.six编写Python脚本,以将大量pdf转换为html,然后将其上传到电子商店。到目前为止,主要文本块已被很好地解析,但是在此过程中,出于明显的原因,我不得不将所有跨度替换为div(并从其属性中删除了跨度),因此现在文档的结构如下:

<div> #first main block
    <div>
        Product desc heading
    </div>
    <div>
        Product desc text
    </div>
    #etc etc
</div>

<div> #second main block
    <div>
        Product specs heading
    </div>
    <div>
        Product specs text
    </div>
    #etc etc
</div>


问题是在相同的div中导航。如果我尝试找到第一个div并向其中添加一些属性,例如docs建议:

firstdiv = soup.find('div')
firstdiv['class'] = 'main_productinfo'


结果是可以预料的-IDLE打印出以下错误:

File "C:\Users\blabla\AppData\Local\Programs\Python\Python37\lib\site-packages\bs4\element.py", line 1036, in __setitem__
    self.attrs[key] = value
TypeError: 'NoneType' object does not support item assignment



,因为find()方法不会返回特定结果(可能找到或可能找不到)。

我想过滤每个文件中的第一个块,然后将表(在下面的specs块中找到)解析为html,并将这两个表加入每个上传文件中。
如何在不将汤一次又一次地转换为字符串的情况下,将属性添加到第一个标签中(并因此使其变得非常丑陋,因为它将新精制的汤转换为没有任何空格)并替换str(soup)中的字符串部分?我对Python还是很陌生,没有什么容易想到的。

UPD:
我在Win 7 64上使用Python 3.7.2。

最佳答案

我没有收到该错误:

import bs4

html = '''<div> #first main block
    <div>
        Product desc heading
    </div>
    <div>
        Product desc text
    </div>
    #etc etc
</div>

<div> #second main block
    <div>
        Product specs heading
    </div>
    <div>
        Product specs text
    </div>
    #etc etc
</div>'''

soup = bs4.BeautifulSoup(html, 'html.parser')

firstdiv = soup.find('div')


输出:

print (firstdiv)
<div> #first main block
    <div>
        Product desc heading
    </div>
<div>
        Product desc text
    </div>
    #etc etc
</div>


然后:

firstdiv['class'] = 'main_productinfo'
print (firstdiv)

<div class="main_productinfo"> #first main block
    <div>
        Product desc heading
    </div>
<div>
        Product desc text
    </div>
    #etc etc
</div>

关于python - 尝试使用BeautifulSoup4在Python中为已解析的PDF文档中的第一个标签设置属性时出现“NoneType”错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55289100/

10-12 18:25
查看更多