【问题标题】:finding HTTPS images with BeautifulSoup, python [closed]使用 BeautifulSoup,python 查找 HTTPS 图像 [关闭]
【发布时间】: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://'
  • 看看urllib.parse
  • 您指定了一个 7 个字符的切片并将其与一个 8 个字符的字符串进行比较。这些永远不可能相等。
  • 一般来说,这正是 Python 字符串具有 startswith 方法的原因,所以你不会犯这样的愚蠢的错误。 (但在这种情况下,您可能应该使用 URL 解析器,正如 @PeterWood 建议的那样。)

标签: python html beautifulsoup


【解决方案1】:

首先,'https://' 是 8 个字符,所以 7 个字符的切片不可能匹配它。

另外,请让您的问题标题实际表明您遇到的问题,而不是对 python 操作员的无关指控。

【讨论】:

  • 完全错过了,谢谢....现在工作
【解决方案2】:

要匹配https:// 字符串,适当的切片将是:8 而不是:7

if image.get('src')[:8] == "https://":

【讨论】:

    猜你喜欢
    • 2023-01-10
    • 1970-01-01
    • 2015-02-20
    • 2019-04-21
    • 2015-09-03
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多