【问题标题】:How to delete this element of html?如何删除这个html元素?
【发布时间】:2020-07-27 08:54:25
【问题描述】:

我正在清理这个url 的html。特别是,我想删除<input checked="" class="selectorOpernerBig" id="default" name="selectorOpernerBig" type="radio">。它的完整 xpath 是/html/body/div/div[1]/div/input。它的结构是

我试图删除

import requests
from bs4 import BeautifulSoup

url = 'https://www.collinsdictionary.com/dictionary/french-english/aimer'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
soup = BeautifulSoup(requests.get(url, headers = headers).content, 'html.parser')
    
remove = soup.find_all('input', {'checked' : ''})  
for match in remove:
    match.decompose()    

entry_name = soup.h2.text
content = ''.join(map(str, soup.select_one('.res_cell_center').contents))

遗憾的是,它会删除 <div class="page" == $0</div> 中的任何内容。能否请您详细说明一下这个问题以及如何解决这个问题?

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    你可以用 BeautifulSoup 做到这一点:

    from bs4 import BeautifulSoup
    
    
    html = '''
    <div class="page"><input type="radio" id="default" class="selectorOpernerBig" name="selectorOpernerBig" checked=""/><label for="default" class="shadow_layer"> </label><label for="default" class="menuPanelCloseButton icon-times icon-2x"> </label></div>
    '''
    
    soup = BeautifulSoup(html, 'html.parser')
    
    remove = soup.find_all('input', {'checked': ''})
    for r in remove:
        r.extract()
    
    print(soup.prettify())
    

    打印:

    <div class="page">
     <label class="shadow_layer" for="default">
     </label>
     <label class="menuPanelCloseButton icon-times icon-2x" for="default">
     </label>
    </div>
    

    如果脚本已经有 BeautifulSoup,最好继续使用 BeautifulSoup 然后导入更多的库。

    【讨论】:

    • 我有类似的命令,例如for match in soup.find_all('div', {'class' : 'example-info'}): for match in soup.find_all('div', {'class' : 'share-overlay'}): 。是否可以将它们合并为一个命令?
    • @LAD 对于特定案例,我无法直接回答。但我可能会将它们分开,以便更轻松地解决任何问题。
    • 请查看我的完整问题here。很抱歉打扰您。
    【解决方案2】:

    另一种方法。

    from simplified_scrapy import SimplifiedDoc, utils, req
    html = '''
    <div class="page"><input type="radio" id="default" class="selectorOpernerBig" name="selectorOpernerBig" checked=""/><label for="default" class="shadow_layer"> </label><label for="default" class="menuPanelCloseButton icon-times icon-2x"> </label></div>
    '''
    doc = SimplifiedDoc(html)
    remove = doc.select('input#default')
    if remove: remove.repleaceSelf('')
    print (doc.html)
    

    结果:

    <div class="page"><label for="default" class="shadow_layer"> </label><label for="default" class="menuPanelCloseButton icon-times icon-2x"> </label></div>
    

    这里有更多示例:https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

    【讨论】:

    • 如果您不介意,请查看this question
    • @LAD 如果您想跳过导入多库,请查看我的答案..
    • @UWTDTV 我也是 :))
    • @LAD 你去什么?
    • @UWTDTV 我也更喜欢使用相同的库来使代码更干净。