Удалить родителей определенных элементов с помощью Javascript [дубликат]Html

Программисты Html
Ответить
Anonymous
 Удалить родителей определенных элементов с помощью Javascript [дубликат]

Сообщение Anonymous »

У меня есть файл Python

Код: Выделить всё

from bs4 import BeautifulSoup
from pathlib import Path
import requests

entryName = "run"
htmlDir = r"C:\Users\Akira\Downloads\Documents"
htmlDir = Path(htmlDir)
outputHtmlDir = Path(htmlDir, "processed_" + entryName + ".html")

headers = {
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'en-US,en;q=0.8',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
}

apiUrl = f"https://en.wiktionary.org/w/rest.php/v1/page/{entryName}/html"
response = requests.get(apiUrl, headers = headers)
response.raise_for_status()

def processHtml2(html, entryName):
"""
html and entryName are string objects
"""
soup = BeautifulSoup(html, 'html.parser')
for d in soup.select('section[data-mw-section-id] > h2[id]'):
if d.text != 'English':
d.parent.extract()
else:
d.clear()
d.string = entryName

for d in soup.select('[id^="Derived_terms"], [id^="Descendants"], [id^="Related_terms"], [id^="See_also"], [id^="Anagrams"], [id^="Alternative_forms"], [property="mw:PageProp/toc"], .disambig-see-also, .audiotable, [id^="Translations"], [id^="Usage_notes"], [id^="Pronunciation_notes"], [id^="Particle"], [id^="Interjection"], [id^="Hyponyms"], [id^="Notes"], [id^="Further_reading"]'):
d.parent.extract()

style = ' '

content = str(soup)
content = "\n".join(line.strip() for line in content.split('\n') if line)
content = content.replace('\n', ' ')
content = entryName + ' ' + style + ' ' + content + ' \n'

return(content)

with open(outputHtmlDir, "w", encoding = "utf-8") as g:
html = processHtml2(response.text, entryName)
g.write(html)
Выше я удаляю родителей определенных элементов из DOM с помощью

Код: Выделить всё

    for d in soup.select('[id^="Derived_terms"], [id^="Alternative_forms"], [id^="Descendants"], [id^="Related_terms"], [id^="See_also"], [id^="Anagrams"], [property="mw:PageProp/toc"], .disambig-see-also, .audiotable, [id^="Translations"], [id^="Usage_notes"], [id^="Pronunciation_notes"], [id^="Particle"], [id^="Interjection"], [id^="Hyponyms"], [id^="Notes"], [id^="Further_reading"]'):
d.parent.extract()
Как мы можем добиться того же эффекта с помощью Javascript? Таким образом, нам не нужно изменять HTML.
Я пробовал

Код: Выделить всё

var matches = document.querySelectorAll('[id^="Alternative_forms"]');
matches.forEach(node => node.parentNode?.remove());
Но это не имеет никакого эффекта:
Изображение


Подробнее здесь: https://stackoverflow.com/questions/798 ... javascript
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»