gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:10 25 4
gpt4 key购买 nike

我尝试使用 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

这里的 .stringNone 因为标题有多个 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

关于python - 字符串参数在我的脚本中表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54314054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com