我想在RSS feed描述标签中获取图像链接。
使用feedparser在discription标签中获取了值。但是我想在该标签中获取图像链接。
<description><![CDATA[<div class="K2FeedImage"><img src="https://srilankamirror.com/media/k2/items/cache/25a3bb259efa21fc96901ad625f3a85d_S.jpg" alt="MP Piyasena sentenced to 4 years in prison" /></div><div class="K2FeedIntroText"><p>Former Tamil National Alliance (TNA) parliamentarian, P. Piyasena has been sentenced to 4 years in prison and fined Rs.</p>
</div><div class="K2FeedFullText">
<p>5.4 million for using state-owned vehicle for an year after losing his parliamentary seat.</p></div>]]></description>
然后我尝试用他的方式在python中使用子字符串。
import re
text = "<![CDATA[<img src='https://adaderanaenglish.s3.amazonaws.com/' width='60' align='left' hspace='5'/>Former Tamil National Alliance (TNA) MP P. Piyasena had been sentenced to 4 years in prison over a case of misusing a state vehicle after losing his MP post. MORE..]]>"
match = re.search("<img src=\"(.+?) \"", text, flags=re.IGNORECASE)
try:
result = match.group(1)
except:
result = "no match found"
print(result)
C:/用户/华硕/台式机/无标题/a.py
未找到匹配项
以退出代码0结束的过程
答案 0 :(得分:1)
您需要稍微更改正则表达式才能使其正常工作。您想要的是在src=
之后获得内容,并在遇到'
字符时立即停止(惰性搜索)。因此,您的正则表达式应为:
match = re.search("src='+(.*?)'",text)
您可以访问this来帮助您使用正则表达式。
答案 1 :(得分:1)
您也可以使用split。这完全取决于您已经隔离了问题中提到的正确标签。因此,您正在使用text
。
text = '''
<description><![CDATA[<div class="K2FeedImage"><img src="https://srilankamirror.com/media/k2/items/cache/25a3bb259efa21fc96901ad625f3a85d_S.jpg" alt="MP Piyasena sentenced to 4 years in prison" /></div><div class="K2FeedIntroText"><p>Former Tamil National Alliance (TNA) parliamentarian, P. Piyasena has been sentenced to 4 years in prison and fined Rs.</p>
</div><div class="K2FeedFullText">
<p>5.4 million for using state-owned vehicle for an year after losing his parliamentary seat.</p></div>]]></description>
'''
link = text.split('src="')[1].split('"')[0]
print(link)
答案 2 :(得分:1)
您可以获得不带正则表达式的图像链接,请尝试以下代码,它将首先找到next_element然后再次获取汤以获取图像链接。
from bs4 import BeautifulSoup
data='''<description><![CDATA[<div class="K2FeedImage"><img src="https://srilankamirror.com/media/k2/items/cache/25a3bb259efa21fc96901ad625f3a85d_S.jpg" alt="MP Piyasena sentenced to 4 years in prison" /></div><div class="K2FeedIntroText"><p>Former Tamil National Alliance (TNA) parliamentarian, P. Piyasena has been sentenced to 4 years in prison and fined Rs.</p>
</div><div class="K2FeedFullText">
<p>5.4 million for using state-owned vehicle for an year after losing his parliamentary seat.</p></div>]]></description>'''
soup=BeautifulSoup(data,'html.parser')
item=soup.find('description')
data1=item.next_element
soup1=BeautifulSoup(data1,'html.parser')
print(soup1.find('img')['src'])
输出:
https://srilankamirror.com/media/k2/items/cache/25a3bb259efa21fc96901ad625f3a85d_S.jpg