gpt4 book ai didi

python - 如何编写一个 BeautifulSoup 过滤器,它只解析标签之间带有特定文本的对象?

转载 作者:太空狗 更新时间:2023-10-29 22:24:13 26 4
gpt4 key购买 nike

我正在使用 Django 和 Python 3.7。我想进行更有效的解析,所以我正在阅读有关 SoupStrainer 对象的信息。我创建了一个自定义的来帮助我只解析我需要的元素......

def my_custom_strainer(self, elem, attrs):
for attr in attrs:
print("attr:" + attr + "=" + attrs[attr])
if elem == 'div' and 'class' in attr and attrs['class'] == "score":
return True
elif elem == "span" and elem.text == re.compile("my text"):
return True

article_stat_page_strainer = SoupStrainer(self.my_custom_strainer)
soup = BeautifulSoup(html, features="html.parser", parse_only=article_stat_page_strainer)

条件之一是我只想解析其文本与特定模式匹配的“span”元素。因此

elem == "span" and elem.text == re.compile("my text")

条款。但是,这会导致

AttributeError: 'str' object has no attribute 'text'

当我尝试运行上面的代码时出错。编写过滤器的正确方法是什么?

最佳答案

TLDR;不,目前这在 BeautifulSoup 中不容易实现(需要修改 BeautifulSoup 和 SoupStrainer 对象)。

解释:

问题是 Strainer 传递的函数在 handle_starttag() 方法上被调用。您可以猜到,您只有开始标记中的值(例如,元素名称和属性)。

https://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/bs4/init.py#L524

if (self.parse_only and len(self.tagStack) <= 1
and (self.parse_only.text
or not self.parse_only.search_tag(name, attrs))):
return None

如您所见,如果您的 Strainer 函数返回 False,该元素将立即被丢弃,而没有机会考虑内部文本(不幸的是)。

另一方面,如果您将“文本”添加到搜索中。

SoupStrainer(text="my text")

它将开始在标签内搜索文本,但这没有元素或属性的上下文 - 你可以看到讽刺:/

将它们组合在一起只会一无所获。而且您甚至无法像 find 函数中所示的那样访问父级: https://gist.github.com/RichardBronosky/4060082

因此目前 Strainer 仅适用于过滤元素/属性。您需要更改大量 Beautiful soup 代码才能使其正常工作。

如果你真的需要这个,我建议继承 BeautifulSoup 和 SoupStrainer 对象并修改它们的行为。

关于python - 如何编写一个 BeautifulSoup 过滤器,它只解析标签之间带有特定文本的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54838079/

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