gpt4 book ai didi

python - BeautifulSoup 中的 .descendants 似乎没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:49 27 4
gpt4 key购买 nike

我正在尝试使用 .replaceWith 替换长 html 网站中的一些元素(类:方法)。为此,我使用 .descendants 并迭代它们以检查 dl 元素是否是我正在寻找的内容。但这仅适用于 0<= X <= 2 个彼此相邻的元素。一行中的每第 3 个到第 n 个元素都被“忽略”。执行相同的代码两次会导致连续 4 个被替换的 dl 元素,依此类推。

for elem in matches:
for child in elem.descendants:
if not isinstance(child, NavigableString) and child.dl is not None and 'method' in child.dl.get('class'):
text = "<p>***removed something here***</p>"
child.dl.replaceWith(BeautifulSoup(text))

(非常愚蠢的)解决方案是找到一行中最大的 dl 元素,将其除以二并经常执行。我希望为此获得一个智能(且快速)的解决方案,并且(更重要的是)了解这里出了什么问题。

编辑:用于测试的html网站是这个:https://docs.python.org/3/library/stdtypes.html错误可以在第4.7.1章字符串方法中看到(那里有很多方法可用)

EDIT_2:但我不仅使用该 html 网站,还使用其中的一部分。 html 部分存储在一个列表中,如果 dl 元素不是第一个 html 元素,我只想“删除”它们(所以如果它是头元素,我想保留该元素)。

总的来说,这就是我的代码的实际外观:

from bs4 import BeautifulSoup, NavigableString

soup = BeautifulSoup(open("/home/sven/Bachelorarbeit/python-doc-extractor-for-cado/extractor-application/index.html"))
f = open('test.html','w') #needs to exist
f.truncate
matches=[]

dl_elems = soup.find_all(['dl'], attrs={'class': ['class', 'method','function','describe', 'classmethod', 'staticmethod']}) # grab all possible dl-elements

sections = soup.find_all(['div'], attrs = {'class':'section'}) #grab all section-elements

matches = dl_elems + sections #merge the lists to get all results

for elem in matches:
for child in elem.descendants:
if not isinstance(child, NavigableString) and child.dl is not None and 'method' in child.dl.get('class'):
text = "<p>***removed something here***</p>"
child.dl.replaceWith(BeautifulSoup(text))


print(matches,file=f)
f.close()

最佳答案

这个想法是找到所有具有 class="method"dl 元素,并将它们替换为 p 标记:

import urllib2
from bs4 import BeautifulSoup, Tag

# get the html
url = "https://docs.python.org/3/library/stdtypes.html"
soup = BeautifulSoup(urllib2.urlopen(url))

# replace all `dl` elements with `method` class
for elem in soup('dl', class_='method'):
tag = Tag(name='p')
tag.string = '***removed something here***'
elem.replace_with(tag)

print soup.prettify()

UPD(适应问题编辑):

dl_elems = soup.find_all(['dl'], attrs={'class': ['class', 'method','function','describe', 'classmethod', 'staticmethod']})   # grab all possible dl-elements
sections = soup.find_all(['div'], attrs={'class': 'section'}) #grab all section-elements

for parent in dl_elems + sections:
for elem in parent.find_all('dl', {'class': 'method'}):
tag = Tag(name='p')
tag.string = '***removed something here***'
elem.replace_with(tag)

print dl_elems + sections

关于python - BeautifulSoup 中的 .descendants 似乎没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230129/

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