【问题标题】:Lstrip and Rstrip won't work, need help removing text from an output in Python 3Lstrip 和 Rstrip 不起作用,需要帮助从 Python 3 的输出中删除文本
【发布时间】:2020-10-18 23:04:57
【问题描述】:

输出是列表的一部分。当我尝试使用 type() 找出输出的类型时,它返回:.

我正在尝试删除“href”左侧的所有内容和“

这是我列表中的输出之一的示例:

<a class="BlogList-item-image-link" href="/new-blog/nova-approval">
<img alt="Nova Approval" data-image="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg" data-image-dimensions="2432x2688" data-image-focal-point="0.5,0.5" data-load="false" data-src="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg"/>
</a>

【问题讨论】:

标签: python list unique strip html-content-extraction


【解决方案1】:

使用lstriprstrip 不是答案。

你试过查看bs4 docs吗?

因为您的输出类型是 bs4 对象。只需找到对象的属性即可获取href

<a class="BlogList-item-image-link" href="/new-blog/nova-approval">
<img alt="Nova Approval" data-image="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg" data-image-dimensions="2432x2688" data-image-focal-point="0.5,0.5" data-load="false" data-src="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg"/>
</a>
from bs4 import BeautifulSoup

soup = BeautifulSoup('html') #put the link there

links = soup.find_all('a') # All of the anchor tags in a list

for link in links:
    print(link.get('href'))

这将打印 HTML 文件中的所有 href 值。

【讨论】:

    【解决方案2】:

    您可能正在尝试提取 href 中的链接。为此,您不需要剥离字符串。您可以通过以下方式进行操作 -

    string =  '''<a class="BlogList-item-image-link" href="/new-blog/nova-approval">
    <img alt="Nova Approval" data-image="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg" data-image-dimensions="2432x2688" data-image-focal-point="0.5,0.5" data-load="false" data-src="https://static1.squarespace.com/static/54ceeff4e4b0d9096117315a/5a3ff7e48165f5d70b78414a/5a504ba90d9297f9a55e4ab6/1516062801655/7P1A5814+cropped.jpg"/>
    </a>'''
    
    
    print( string[string.find('href="')+6:string.find('>')-1] )
    

    输出:

    /new-blog/nova-approval
    

    在上面的print() 语句中,string.find('href="') 将返回该字符串的索引,然后我们从该索引 + 6 循环到 href 标记的末尾。这是假设&gt; 紧跟在href 之后。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多