首页 > 解决方案 > 通过将其与列表(Python)进行比较从网页中删除项目

问题描述

我已经在需要删除的列表中收集了数据,下面的代码显示了该列表:

keyword= "www.indigo.com"
hrefs = [links['href'] for links in getDetails.find_all('a', href=True) if target in links['href']]
print(hrefs)

它打印以下输出:

['https://www.indigo.com/registration.html']
[]
['https://www.indigo.com/buservfcl.html', 'https://www.indigo.com/2021/07/agents.html']

getDetails有完整的页面源代码

现在,我如何getDetailshrefs列表进行比较并删除/分解列表中存在的每个项目。

我试过这个,但由于某种原因它不起作用:

hrefs = [links['href'] for links in getDetails.find_all('a', href=True) if target in links['href']]
print(hrefs)
for z in hrefs:
    getDetails.decompose()

它删除了 getDescription 中的全部数据,但我只需要删除列表中的元素而不是 evrything

输出应该是完整的 HTML,除了包含www.indigo.com的那些

标签: pythonlistweb-scrapingbeautifulsoup

解决方案


你必须找到parent标签然后使用decompose()方法

html="""<div><a href="www.indigo.com"></div>"""

soup=BeautifulSoup(html,"html.parser")

target= "www.indigo.com"
href_tags = [links for links in soup.find_all('a', href=True) if target in links['href']]

for i in href_tags:
    i.parent.decompose()

输出:

soup将是空的

从网址:

import requests
res=requests.get("https://www.assamcareer.com/2021/06/oil-india-limited.html")
soup=BeautifulSoup(res.text,"html.parser")
target= "www.assamcareer.com"
tags = [links for links in soup.find_all('a', href=True) if target in links['href']]
for i in tags:
    i.parent.decompose()

更新答案:

for title in root:
    /
 
        Your code

    /
    href_tags = [links for links in getDetails.find_all('a',href=True) if target in links['href']]
    print(href_tags)

for i in href_tags:
    i.parent.decompose()

推荐阅读