[英]Lstrip and Rstrip won't work, need help removing text from an output in Python 3
output 是列表的一部分。 当我尝试使用 type() 找出输出的类型时,它返回:<class 'bs4.element.Tag'>。
我正在尝试删除“href”左侧的所有内容和“<img”右侧的所有内容。 我尝试过 lstrip 和 rstrip 但它们不起作用,因为我列表中的每个 output 都是唯一的。 尽管列表中的每个 output 都是唯一的,但它们都具有与“href”和“<img”相同的格式。
这是我列表中的输出之一的示例:
<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>
您可能正在尝试提取 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] )
Output:
/new-blog/nova-approval
在上面的print()
语句中, string.find('href="')
将返回该字符串的索引,然后我们从该索引 + 6 循环到 href 标记的末尾。假设>
紧跟在href
之后.
希望这可以帮助 !
使用lstrip
和rstrip
不会是答案。
您是否尝试过查看bs4 文档?
因为你的 output 的类型是 bs4 object。 您可以找到 object 的属性来获取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
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.