【问题标题】:How to strip this link to remove unwanted data (bs4)?如何剥离此链接以删除不需要的数据(bs4)?
【发布时间】:2022-08-20 19:12:52
【问题描述】:

这是 HTML 的样子:

<div class=\"full-news none\">
     Demo: <a href=\"https://www.lolinez.com/?https://www.makemytrip.com\" 
    rel=\"external noopener noreferrer\" target=\"_blank\">https://www.makemytrip.com</a>
   <br/>

如何从 href:https://www.lolinez.com/? 中删除这部分,使最终输出变成这样:

 <div class=\"full-news none\">
         Demo: <a href=\"https://www.makemytrip.com\" 
        rel=\"external noopener noreferrer\" target=\"_blank\">https://www.makemytrip.com</a>
       <br/>

我曾尝试使用美汤的decompose 功能,但它完全删除了整个标签,请问如何解决?

  • 您能否扩展您的问题并澄清为什么您不能只是 find&replace 或其他形式的替换?
  • 为什么要手动查找和替换好友?自动化的东西,这就是python的乐趣......我猜......
  • 您可以在 python 中自动查找替换。如果那是一个合适的解决方案,那么您可以使用 replace() geeksforgeeks.org/python-string-replace
  • 我知道,但是如何在这个 html 结构中导航,然后执行所需的操作,如果您知道解决方案,请告诉我
  • 如果没有更多关于您为什么要具体执行此操作的上下文(因此我的原始评论)很难说,但这可能对您有用:stackoverflow.com/questions/459981/… 您只能选择某些链接来使用普通的 bs4 技术进行修改。

标签: python html web-scraping beautifulsoup


【解决方案1】:

笔记 如果没有额外的背景,我会缩小到以下方法

选项1

将您传递给BeautifulSoup 构造函数的string 替换为子字符串:

soup = BeautifulSoup(YOUR_STRING.replace('https://www.lolinez.com/?',''), 'lxml')
选项#2

替换soup 中的子字符串,您可以选择所有包含www.lolinez.com&lt;a&gt; 并替换其href 的值:

for x in soup.select('a[href*="www.lolinez.com"]'):
    x['href'] = x['href'].replace('https://www.lolinez.com/?','')

例子

import bs4, requests
from bs4 import BeautifulSoup

html='''
<a href="https://www.lolinez.com/?https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a>
<a href="https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a>
<a href="https://www.lolinez.com/?https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a>
'''

soup = BeautifulSoup(html, 'lxml')

for x in soup.select('a[href*="www.lolinez.com"]'):
    x['href'] = x['href'].replace('https://www.lolinez.com/?','')
    
soup

输出

<html><body><a href="https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a><a href="https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a><a href="https://www.makemytrip.com" rel="external noopener noreferrer" target="_blank">https://www.makemytrip.com</a></body></html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多