Skip to main content
 首页 » 编程设计

python之字符串参数在我的脚本中表现不同

2025年05月04日37虾米哥

我尝试使用 string argument 从一些 html 元素中解析文本此处描述的方式却惨遭失败。我尝试了两种不同的方法,但每次遇到相同的 AttributeError。

在这种情况下,我如何使用字符串参数来获取文本?

我试过:

import re 
from bs4 import BeautifulSoup 
 
htmlelement = """ 
<caption> 
    <span class="toggle open"></span> 
    ASIC registration 
</caption> 
""" 
soup = BeautifulSoup(htmlelement,"lxml") 
try: 
    item = soup.find("caption",string="ASIC registration").text 
    #item = soup.find("caption",string=re.compile("ASIC registration",re.I)).text 
except AttributeError: 
    item = "" 
print(item) 

预期输出(仅使用字符串参数):

ASIC registration 

请您参考如下方法:

How can I use string argument in this very case to fetch the text?

你不能

注意: 我假设您的意思是

中的一些更改字符串参数
item = soup.find("caption",string="ASIC registration").text 

在 documentation 中给出

If a tag has only one child, and that child is a NavigableString, the child is made available as .string:

import re 
from bs4 import BeautifulSoup 
htmlelement = """ 
<caption> 
    <span class="toggle open"></span> 
    ASIC registration 
</caption> 
""" 
soup = BeautifulSoup(htmlelement,"lxml") 
item = soup.find("caption") 
print(item.string) 

输出

None 

这里的 .string 是 None 因为标题有多个 child 。

如果你想用文本获取父级(在本例中为标题标签),你可以这样做

item = soup.find(string=re.compile('ASIC registration')).parent 

这将给

<caption><a></a>ASIC registration</caption> 

当然,在这个父标签上调用 .text 将给出该标签内的全文,如果它不是其中的全文的话。

item = soup.find(string=re.compile('ASIC')).parent.text 

将给出一个输出

ASIC registration