首页 > 解决方案 > 虽然文本不在汤中:-即使存在,也没有捡起该文本在汤中

问题描述

编写脚本以检查产品是否已加载到网站上。

import requests
import time
from bs4 import BeautifulSoup

r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js')
soup = BeautifulSoup(r.text, 'html.parser')
text = '3.0'

while text not in soup:
    print('not found')
    r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js')
    soup = BeautifulSoup(r.text, 'html.parser')
    time.sleep(5)

当我打印汤时,我可以看到“3.0”在那里。但是当我运行脚本时,它无法识别“3.0”的存在。我究竟做错了什么?

标签: pythonpython-3.xbeautifulsoup

解决方案


如果您只想检查源代码中是否存在文本,则不需要BeautifulSoup. 您可以直接使用requests.

r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js')
text = '3.0'

while text not in r.text:
    print('not found')
    r = requests.get('https://www.off---white.com/en/GB/section/new-arrivals.js')
    time.sleep(5)

如果您因任何其他原因需要使用BeautifulSoup,您可以使用以下任意一种:

  • while text not in soup.text
  • while text not in soup.get_text()
  • while text not in str(soup)

现在,如果您对为什么while text not in soup不起作用感到好奇,请阅读以下内容:

定义的行为的魔术方法是。如果你查看 的源代码,它是由以下给出的:x in y__contains__(self, item)BeautifulSoup.__contains__

def __contains__(self, x):
    return x in self.contents

因此,通过使用while text not in soup,您正在检查是否是由 .返回text的元素列表项(或Tag或) 。因为,是标签内的一些文本,它不能直接在该列表中可用,因此返回.NavigableString.contents3.0'3.0' in soupFalse


要检查源代码,您可以转到 PC 上安装的库并检查代码,或使用以下方法:

import inspect
from bs4 import BeautifulSoup

print(inspect.getsource(BeautifulSoup.__contains__))

推荐阅读