python - 虽然文本不在汤中:-即使存在,也没有捡起该文本在汤中
问题描述
编写脚本以检查产品是否已加载到网站上。
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”的存在。我究竟做错了什么?
解决方案
如果您只想检查源代码中是否存在文本,则不需要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
.contents
3.0
'3.0' in soup
False
要检查源代码,您可以转到 PC 上安装的库并检查代码,或使用以下方法:
import inspect
from bs4 import BeautifulSoup
print(inspect.getsource(BeautifulSoup.__contains__))
推荐阅读
- javascript - Vuejs 从头部隐藏样式标签 | Laravel-vuejs 应用程序
- python - 将视图中的函数转换为异步函数。django/python
- python - 如何更改 Odoo 10 中的“oe_chatter”日志评论?
- angular - 首次应用渲染后延迟模块预加载
- powershell - powershell base64编码不同的结果
- python - 如何在 SymPy 中使用 nonlinsolve 返回有限(浮点)值?
- typescript - 如何在没有冲突的情况下将 Mocha 和 Jest 与 TypeScript 一起使用?
- amazon-web-services - 在 AWS Lambda 中运行 selenium 测试 (chrome) - NET Core
- angular7 - 如何修改从 observable 获取的数据?
- ansible - 如何避免类型转换警告?