python - 通过将其与列表(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
有完整的页面源代码
现在,我如何
getDetails
与hrefs
列表进行比较并删除/分解列表中存在的每个项目。
我试过这个,但由于某种原因它不起作用:
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的那些
解决方案
你必须找到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()
推荐阅读
- angular - 向父组件发送数据表单
- java - 部署成功后的404
- botframework - 微软示例 52 -
- reactjs - 如何在firebase实时数据库和身份验证上生成相同的用户ID
- quarkus - Quarkus、Apache 目录 api、google libphonenumber 库不适用于本机
- sql - Oracle 中的转置功能
- php - Wordpress 类别页面在 URL 中显示类别和子类别
- netbeans - NetBeans Junit5 测试输出忽略 DisplayName 嵌套格式
- javascript - 如何修复 Express Route 处理程序中丢失的 SocketIO 会话数据?
- node.js - 让 Vue 应用程序正确读取 Heroku 上设置的环境变量的最佳方法是什么?