python - 使用 Python 抓取数据并接收与 DevTools 不同的 html 树
问题描述
我正在尝试从网站zara.com 抓取数据,我已经弄清楚如何使用列表中的一组项目解析父元素,但我想更深入地挖掘并打开每个项目链接并获取有关它的其他信息.
所以,我使用了这种代码:
import requests
import time
from bs4 import BeautifulSoup
ListWithRequests = ['https://www.zara.com/nl/en/plain-shirt-p06608389.html'] # In this example only one item
for item in ListWithRequests:
response = requests.get(item,verify=False)
soup2 = BeautifulSoup(response.text, "html.parser")
soup2.prettify()
time.sleep(1)
f = open("demo.html","w+")
f.write(response.text)
例如我想收到商品的价格,在开发工具中它是块
<span class="main_price">25.95 EUR</span>
或项目 ID
<div clas="product-info-wrapper _product-info">
<p class="product-color">
<span class="_colorName">**White**
</span>
</p>
</div>
但是在demo.html文件中,我收到了完全不同的树,并且找不到我需要的任何元素。
请告诉我我做错了什么
解决方案
页面是通过 加载的JavaScript
,因此bs4
将无法呈现它。您可以selenium
在这种情况下使用,但我注意到您要查找的数据实际上显示在script
标签中,您可以轻松加载它JSON
或快速捕获,我使用过re
:
import requests
import re
def main(url):
r = requests.get(url)
price = re.search(r'\"price\": \"(.*?)\"', r.text).group(1)
print(price)
main("https://www.zara.com/nl/en/plain-shirt-p06608389.html")
输出:
25.95
推荐阅读
- apache-spark - Pyspark - 根据单词列表检查列字符串并删除
- javascript - 为什么自动检测 otp 没有在 React 中渲染代码
- android - 如何在没有 Partial_Wakelock 的情况下让我的应用程序也以打盹模式运行?
- c++ - 多线程管理器
- php - 如何正确关闭 OOP PHP 数据库连接?
- bash - 使用 awk 命令的 bash 脚本中的语法错误
- asp.net-core - 无法使用 Ubuntu 20.04 使 Net5 工作(OpenSSL 连接问题)
- matlab-figure - 在matlab中手动进行卷积
- spring - Spring Data Cassandra 不处理原始 UDTS,不抛出合适的转换器异常
- javascript - 无法从 React 中的路径渲染图像