python - 试图抓取网页。下载的 html 代码与现场代码略有不同
问题描述
我是网络抓取的新手,我正在尝试为网站 pokemoncenter.com 构建一个非常基本的股票跟踪器。访问直播网站上商品的产品页面时,添加到购物车按钮显示为:
<button type="button" class="jsx-2748458255 product-add btn btn-secondary">Add to Cart</button>
当商品缺货时,按钮为:
<button type="button" disabled="" class="jsx-2748458255 product-add btn btn-tertiary disabled">Out of Stock</button>
但是每当我尝试抓取网站时,无论该项目是否有库存,按钮都是:
<button class="jsx-2748458255 product-add btn btn-tertiary disabled" disabled="" type="button"></button>
所以本质上,当我使用 requests.get() 下载 html 代码时,它总是显示为缺货。
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen, Request
import requests
page_url = "https://www.pokemoncenter.com/product/701-00364/primal-groudon-poke-plush-17-3-4-in"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'}
req = requests.get(page_url, headers = headers)
page_soup = soup(req.text, "html.parser")
#Find add to cart button
divs = page_soup.findAll("div", {"class" : "jsx-829839431 product-col"})
button = str(divs[1].find("button", {"class" : "jsx-2748458255"}))
#Check if button is disabled or not
if (button.find('disabled') != -1):
print("Out of Stock")
else:
print("In Stock")
有货示例:https
://www.pokemoncenter.com/product/701-00364/primal-groudon-poke-plush-17-3-4-in
缺货示例:https ://www.pokemoncenter.com/产品/701-06558/gigantamax-pikachu-poke-plush-17-in
解决方案
正如goalie1998 所提到的,该站点可以使用javascript 来仅首先加载必要的图像以减少初始加载时间。您可能仍然可以使用Selenium来抓取该网站,因为它可以模仿浏览器的行为。
推荐阅读
- python - pd.to_datetime() 返回类型会因输入而异。如何确保它不返回具有 dtype 'object' 的系列/数组?
- php - WP rest 自定义路由认证
- spring-batch - 如何使用基于块的处理处理 Spring 批处理中的项目列表| 在 Chunk 中批量处理项目
- javascript - 如何将图标放在我的电子应用程序中?
- profiling - sycl::info::event_profiling 中的 command_submit 提交整个代码还是仅提交并行?
- node.js - Webdriver IO如何将Excel文件存储在缓存中并从Node JS上的缓存中调用
- elasticsearch - Elasticsearch Query DSL 多个“查询”
- azure-web-app-service - 如何测量性能评估期间消耗的 ACU(Azure 计算单元)?
- javascript - 当我向 Redux 存储添加数据时,结果为 null
- javascript - 捕获用户在 HTML 表单中输入的数据,并将其显示在同一页面上