【发布时间】:2018-12-22 08:40:37
【问题描述】:
我正在遍历 request.POST 中的所有 img 以查看它们是否为 HTTPS(我正在使用 Beautiful Soup 提供帮助)
这是我的代码:
content = request.POST['content']
print(content) #prints:
<p>test test test</p><br><p><img src="https://www.treefrogfarm.com/store/images/source/IFE_A-K/ClarySage2.jpg" alt=""></p><br><p>2nd 2nd</p><br><p><img src="https://www.treefrogfarm.com/store/images/source/IFE_A-K/ClarySage2.jpg" alt=""></p>
soup = BeautifulSoup(content, 'html.parser')
for image in soup.find_all('img'):
print('Source:', image.get('src')[:8]) #prints Source: https://
if image.get('src')[:7] == "https://":
print('HTTPS')
else:
print('Not HTTPS')
即使image.get('src')[:7] == "https://",代码仍然会打印Not HTTPS。
知道为什么吗?
【问题讨论】:
-
'https:/' != 'https://' -
您指定了一个 7 个字符的切片并将其与一个 8 个字符的字符串进行比较。这些永远不可能相等。
-
一般来说,这正是 Python 字符串具有
startswith方法的原因,所以你不会犯这样的愚蠢的错误。 (但在这种情况下,您可能应该使用 URL 解析器,正如 @PeterWood 建议的那样。)
标签: python html beautifulsoup