我无法通过获取方法Python,请求获取页面的html代码。get 方法返回一些奇怪的代码



不好意思

我还在学习

我有这个代码

import requests
import os
os.system('CLS')
r = requests.get('https://kazanexpress.ru/product/736692')
with open('file.html','w',encoding='utf-8') as file:
file.write(r.text)

在file。html中我找到了

<!DOCTYPE html><html lang=ru><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1"><meta http-equiv=content-language content=ru><meta name=description content="Маркетплейс выгодных цен с бесплатной доставкой за сутки."><meta name=keywords content="маркетплейс, интернет-магазин, доставка на следующий день, низкие цены, купить дешево, быстрая доставка, лучшие цены"><meta id=prerender-status-code name=prerender-status-code content=200><meta id=prerender-header name=prerender-header content=""><title>KazanExpress - шопинг с бесплатной доставкой за 1 день</title><link rel=icon type=image/png sizes=32x32 href=/static/img/icons/favicon-32.png><link rel=icon type=image/png sizes=16x16 href=/static/img/icons/favicon-16.png><meta name=ROBOTS content="INDEX, FOLLOW"><meta property=og:url content=""><meta property=og:title content=""><meta property=og:description content=""><meta property=og:image itemprop=image content=""><meta property=og:image:secure_url content=""><meta property=og:type content=website><meta property=product:brand content=""><meta property=product:availability content=""><meta property=product:condition content=new><meta property=product:price:amount content=""><meta property=product:retailer_item_id content=""><meta property=product:price:currency content=RUB><link rel=canonical href=https://kazanexpress.ru/ ><link itemprop=thumbnailUrl href=url_image><meta name=twitter:image content=""><meta name=apple-itunes-app content="app-id=1438104323"><meta name=facebook-domain-verification content=rb1tipol8glrbndktmbkyom0xaqomi><meta name=google-site-verification content=ffMsQuJJt9A3n3pN6FcpIKq8UcuWj1gvjMdvqLxEwMI><meta name=google-site-verification content=QrVT-SLKbPGSA5shhmMLeS9ilfJ-V7IoNDb3pxgHvt4><meta name=google-site-verification content=_Jd4DyFIJ-LlvrfYl7nq9VsJGU0Dl-fSewUtb8xFY1M><meta name=google-site-verification content=22lwQj3aZEg4S0p9e0z4t561wEmGC5q1u3yxbu7qAC8><meta name=google-site-verification content=R674rCopA_NzCaJ7A72UfmTkpXBUyudgh0a4u_JznQE><meta name=google-site-verification content=86eWgZxBzwHcvvnNMA8WPOAxjOOesyMvyQBzz3BW3BQ><meta name=mailru-verification content=2be7cbd6459741ed><meta name=yandex-verification content=1737294911c38a7a><meta name=yandex-verification content=c1a636f058f5aae4><meta name=yandex-verification content=12e93a30f6213678><meta name=mailru-verification content=67628f3035f4dc15><!--[if IE]><link rel="shortcut icon" href="/static/img/icons/favicon.ico"><![endif]--><meta name=theme-color content=#E53935><meta name=apple-mobile-web-app-capable content=yes><meta name=apple-mobile-web-app-status-bar-style content=white><meta name=apple-mobile-web-app-title content=KazanExpress><link rel=apple-touch-icon href=/static/img/icons/apple-touch-icon.png><link rel=mask-icon href=/static/img/icons/safari-pinned-tab.svg color=#e53935><meta name=msapplication-TileImage content=/static/img/icons/mstile-144x144.png><meta name=msapplication-TileColor content=#FFF><script nomodule type=text/javascript src=https://cdn.polyfill.io/v2/polyfill.min.js defer=defer></script><link rel=stylesheet href=/static/css/styleoff.css><link rel=stylesheet href=/static/css/fonts.css><link rel=stylesheet href=/static/css/typebase.css><link rel=stylesheet href=/static/css/helpers.css><script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default-3.6,fetch" defer=defer></script><script>(
function(w,d,s,l,i) {
w[l]=w[l]||[];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),
dl=l!='dataLayer'?'&l='+l:'';
window.dataLayer = window.dataLayer || [];
j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-KTRMJ4R');</script><script type=text/javascript src=https://vk.com/js/api/openapi.js?158 onload="function onload() { VK.Retargeting.Init('VK-RTRG-1007905-4evhc'), VK.Retargeting.Hit() }"></script><script type=text/javascript>// Just in case
if (!window.VK) {
window.VK = {}; VK._protocol = 'https:'; VK._base_domain = ''; if (!VK.Retargeting) { VK.Retargeting = { pixelCode: null, Init: function (pixelCode) { this.pixelCode = pixelCode; return this }, Event: function (event) { if (!this.pixelCode) { return } (window.Image ? (new Image()) : document.createElement('img')).src = 'https://vk.com/rtrg?p=' + this.pixelCode + (event ? ('&event=' + encodeURIComponent(event)) : '') }, Hit: function () { this.Event() }, Add: function (audienceID) { if (!this.pixelCode || !audienceID) { return } (window.Image ? (new Image()) : document.createElement('img')).src = 'https://vk.com/rtrg?p=' + this.pixelCode + '&audience=' + encodeURIComponent(audienceID) } } };
}
VK.Retargeting.Init('VK-RTRG-1007905-4evhc');
VK.Retargeting.Hit();</script><noscript><img src="https://vk.com/rtrg?p=VK-RTRG-1007905-4evhc" style="position:fixed; left:-999px;" alt=""></noscript><script type=text/javascript>!function(){var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="https://vk.com/js/api/openapi.js?168",t.onload=function(){VK.Retargeting.Init("VK-RTRG-547218-gUAWw"),VK.Retargeting.Hit()},document.head.appendChild(t)}();</script><noscript><img src="https://vk.com/rtrg?p=VK-RTRG-547218-gUAWw" style="position:fixed; left:-999px;" alt=""></noscript><script defer=defer src=/static/js/app.3d0e36da4f33b0696aa2.js?55e750b3c45d2da95e4e></script></head><body><app></app><noscript><div style="width: 100%;text-align: center;transform: translateY(50vh);transform: translateY(calc(50vh - 50%));"><svg id=Layer_1 data-name="Layer 1" xmlns=http://www.w3.org/2000/svg viewBox="0 0 76.73 76.88" style="width: 36px;height: 36px;"><defs><style>.cls-1 {
fill: #e53935;
}</style></defs><title>KazanExpress</title><path class=cls-1 d=M56.06,53.61H47.74L35.36,37.88h0L47.51,23.27h8.31L45.94,35.15H76.73a38.44,38.44,0,1,0,0,6.58h-30Zm-23.12,0H26.36V23.27h6.58V53.61Z></path></svg><p>Пожалуйста, включите JavaScript, чтобы воспользоваться сайтом!</p></div></noscript><script type=text/javascript>var _tmr = window._tmr || (window._tmr = []);
_tmr.push({id: "3210365", type: "pageView", start: (new Date()).getTime()});
(function (d, w, id) {
if (d.getElementById(id)) return;
var ts = d.createElement("script"); ts.type = "text/javascript"; ts.async = true; ts.id = id;
ts.src = "https://top-fwz1.mail.ru/js/code.js";
var f = function () {var s = d.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ts, s);};
if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); }
})(document, window, "topmailru-code");</script><noscript><div><img src="https://top-fwz1.mail.ru/counter?id=3210365;js=na" style=border:0;position:absolute;left:-9999px; alt=Top.Mail.Ru></div></noscript><script type=text/javascript>var axel = Math.random() + "";
var a = axel * 10000000000000;
document.write('<iframe src="https://9943304.fls.doubleclick.net/activityi;src=9943304;type=visitors;cat=kazan0;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');</script><noscript><iframe src="https://9943304.fls.doubleclick.net/activityi;src=9943304;type=visitors;cat=kazan0;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=; ord=1?" width=1 height=1 frameborder=0 style=display:none></iframe></noscript><script>mindbox = window.mindbox || function() { mindbox.queue.push(arguments); };
mindbox.queue = mindbox.queue || [];</script><script>mindbox('create', { endpointId: 'kazanexpress-website' });</script><script src=https://api.mindbox.ru/scripts/v1/tracker.js async></script><noscript><div><img src="//top-fwz1.mail.ru/counter?id=3052180;js=na" style=border:0;position:absolute;left:-9999px; alt=""></div></noscript><script type=text/javascript>!function () { var t = document.createElement("script"); t.type = "text/javascript", t.async = !0, t.src = "https://vk.com/js/api/openapi.js?158", t.onload = function () { VK.Retargeting.Init("VK-RTRG-1007905-4evhc"), VK.Retargeting.Hit() }, document.head.appendChild(t) }();</script><noscript><img src="https://vk.com/rtrg?p=VK-RTRG-1007905-4evhc" style="position:fixed; left:-999px;" alt=""></noscript><noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KTRMJ4R" height=0 width=0 style=display:none;visibility:hidden></iframe></noscript><link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:400,500,700&amp;subset=cyrillic" preload></body></html>
如你所见,点击这个url: https://kazanexpress.ru/product/736692

的HTML代码不是我需要的,当我打开它只是一个白色的屏幕。我怎样才能得到真正的html代码?

这不是一个普通的HTML页面,它在页面代码中嵌入了JS。此代码将在接受页面后执行,并用于获取服务器呈现的页面,因此您需要发出其他请求来获取页面中的信息,这只是其中的几个例子。

https://api.kazanexpress.ru/api/v2/product/736692

这是服务器生成的数据的临时URL,当你点击它时可能是无效的,但是你可以在这里看到数据。

{"payload":{"data":{"id":736692,"title":"Смартфон realme C11 2021 2+32GB (NFC)","category":{"id":12690,"title":"Смартфоны","productAmount":183,"parent":{"id":10044,"title":"Смартфоны и телефоны","productAmount":41925,"parent":{"id":10020,"title":"Электроника","productAmount":66655,"parent":null}}},"rating":4.9,"reviewsAmount":18,"ordersAmount":226,"rOrdersAmount":200,"totalAvailableAmount":14,"charityCommission":0,"description":"<h1 class="ql-align-center">Смартфон realme C11 2021</h1><p class="ql-align-center"><img src="https://image-cdn.kazanexpress.ru/c8bkdcghmedd7lh3b2ug/original.jpg"></p><p class="ql-align-center"><a href="https://kazanexpress.ru/product/Avtomobilnoe-zaryadnoe-ustrojstvo-704090"><img src="https://image-cdn.kazanexpress.ru/c8bkhr8knioe95m0nghg/original.jpg"></a><a href="https://kazanexpress.ru/product/Chekhol-knizhka-universalnyj-dlya-703999"><img src="https://image-cdn.kazanexpress.ru/c8hk4c5irr08a1l3sf40/original.jpg"></a><a href="https://kazanexpress.ru/product/Zaschitnoe-steklo-Gresso-594030"><img src="https://image-cdn.kazanexpress.ru/c981b927dhhsgj7hmirg/original.jpg"></a></p><h1 class="ql-align-center">Смартфон realme C11 2021 2+32</h1><p class="ql-align-center"><img src="https://moneyfromnothing.ru/phones/realme-c11-2021/pics/realme-c11-2021.jpg"></p><p class="ql-align-center">Realme C11 2021 – стильный смартфон с производительным процессором Octa Core и ёмкой батареей для активных пользователей.</p><p class="ql-align-center"><img src="https://sw.cool3c.com/user/29442/2021/f02eeee4-7f34-4cce-aeb6-2e7a0a8907a0.jpg?fit=max&amp;w=1400&amp;q=80"></p><h1 class="ql-align-center">ВСЕГДА НА СВЯЗИ</h1><p>Запаса в 5000 мАч благодаря опции суперэнергоэффективности хватает на срок до 43 дней при использовании режима ожидания, до 38 часов разговоров и до 19 – при просмотре фильмов и клипов нон-стоп. Функция реверсивной зарядки позволит восполнять ресурс аккумулятора внешних устройств с беспроводным интерфейсом, например смарт-часов или наушников.</p><p class="ql-align-center"><img src="https://img.blogs.es/realme/wp-content/uploads/2021/10/Abre_realmeC11-1080x675.jpeg"></p><h1 class="ql-align-center">БОЛЬШЕ УДОВОЛЬСТВИЯ</h1><p>Иммерсивный HD+ экран диагональю 6,5 дюймов создаёт эффект полного погружения в картинку. Соотношение сторон 20:9 оптимально для разного мультимедийного контента. Возможностей основной камеры на 8 Мп с поддержкой HRD хватает для съёмки чётких видео при движении, детализированных панорам и качественных портретов с распознаванием лиц. Бьютификация обеспечивает красивые и естественные селфи.</p><p><br></p><h1 class="ql-align-center">ВСЁ ПОД РУКОЙ</h1><p>В тройном слоте есть модули для двух SIM и одной microSD. Объём памяти 2+32 Гб можно расширить за счёт дополнительной карты до 256 Гб – этого достаточно, чтобы не думать о том, хватит ли места для фото, игр и приложений.</p>","comments":[],"attributes":["Диагональ экрана: 6.52"","Объем памяти: 2Гб оперативная, 32Гб встроенная","Тройной слот: 2 SIM + 1 MicroSD","Версия ОС: Android 11 Go","Количество ядер: 8","Частота работы процессора: 1.6 ГГц","Количество мегапикселей камеры: 8 Мп, 5 Мп","NFC: Да"],"tags":[],"synonyms":[],"photos":[{"photo":{"800":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/original.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_low.jpg"},"720":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/original.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_low.jpg"},"480":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_540_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_540_low.jpg"},"240":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_low.jpg"},"80":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_80_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_80_low.jpg"},"24034":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_low.jpg"},"120":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_240_low.jpg"},"540":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_540_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_540_low.jpg"},"60":{"high":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_80_high.jpg","low":"https://ke-images.servicecdn.ru/carvn69prp4amo508f80/t_product_80_low.jpg"}},"photoKey":"carvn69prp4amo508f80","color":"#0549be","hasVerticalPhoto":false},{"photo":{"800":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/original.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_low.jpg"},"720":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/original.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_low.jpg"},"480":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_540_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_540_low.jpg"},"240":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_low.jpg"},"80":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_80_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_80_low.jpg"},"24034":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_low.jpg"},"120":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_240_low.jpg"},"540":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_540_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_540_low.jpg"},"60":{"high":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_80_high.jpg","low":"https://ke-images.servicecdn.ru/carvn79slg8l47n5976g/t_product_80_low.jpg"}},"photoKey":"carvn79slg8l47n5976g","color":"#000000","hasVerticalPhoto":false}],"video":null,"hasCircularPhotos":false,"circularPhotosList":[],"characteristics":[{"id":-1,"title":"Цвет","values":[{"id":-125,"title":"Синий","value":"#0549be"},{"id":-1,"title":"Черный","value":"#000000"}]}],"productOptionDtos":[],"skuList":[{"id":1973578,"characteristics":[{"charIndex":0,"valueIndex":0}],"availableAmount":2,"fullPrice":10490.00,"charityProfit":0.00,"purchasePrice":7990.00,"barcode":6941399045385,"address":null,"offer":null,"discountBadge":null,"installment":{"payment":1331.67,"monthAmount":6},"productOptionDtos":[],"vat":{"type":"NONE","vatRate":0,"vatAmount":0.00,"price":7990.00}},{"id":1973579,"characteristics":[{"charIndex":0,"valueIndex":1}],"availableAmount":12,"fullPrice":10490.00,"charityProfit":0.00,"purchasePrice":7990.00,"barcode":6941399045392,"address":null,"offer":null,"discountBadge":null,"installment":{"payment":1331.67,"monthAmount":6},"productOptionDtos":[],"vat":{"type":"NONE","vatRate":0,"vatAmount":0.00,"price":7990.00}}],"seller":{"id":5491,"title":"texnikaprо","link":"texnikapro","banner":null,"avatar":null,"description":"Дарим ПРОМОКОД на смарт-часы и фитнес браслеты при покупке смартфона от 10.000р в нашем магазине! n(*Акция действует только после доставки смартфона)nnНаша компания работает с 2000 года.nНа данный момент в сети 87 салонов связи и продолжают открываться новые. nМы являемся официальными дистрибьюторами крупнейших брендов электроники на территории Российской Федерации.nВсе наши товары являются продуктами с сертификацией РОСТЕСТ и ЕАС, с официальной гарантией производителя.nПриятных покупок.","hasCharityProducts":false,"registrationDate":1633609649320,"rating":4.6,"reviews":3607,"orders":41605,"official":false,"contacts":[],"categories":[],"currentCategory":null,"filters":[],"appliedFilters":[],"priceFilter":null,"totalProducts":0,"parents":[],"products":[],"sellerAccountId":2975961,"info":null},"topFeedback":{"reviewId":1484280,"productId":736692,"date":1629135570249,"edited":false,"customer":"Евгений","reply":{"id":619572,"date":1629276520205,"edited":true,"content":"Благодарим Вас за выбор нашего магазина и за высокую оценку товара. Мы очень рады, что вы остались довольны покупкой. В нашем магазине большой выбор качественной электроники и аксессуаров, ознакомиться с ассортиментом можно по следующей ссылке https://kazanexpress.ru/texnikapro . Мы всегда к Вашим услугам, ждем Вас снова!","shop":"texnikaprо","photos":[],"liked":null,"disliked":null},"rating":5,"characteristics":[{"characteristic":"Цвет","characteristicValue":"Черный"}],"pros":null,"cons":null,"content":"Сегодня в 5:20 был совершён заказ, сегодня ж вечером телефончик ждал меня в пункте выдачи. Спасибо продавцу за оперативность.","photos":[],"status":"PUBLISHED","hasVerticalPhoto":null,"like":false,"dislike":false,"amountLike":0,"amountDislike":0,"id":29108868,"isAnonymous":false},"isEco":false,"isPerishable":false,"hasVerticalPhoto":true,"showKitty":false,"bonusProduct":false,"badges":[],"volumeDiscount":null,"colorPhotoPreview":true,"adultCategory":false,"favourite":false},"promotion":null},"timestamp":[2022,7,17,18,6,27,148297000]}

如您所见,它是JSON格式的数据字符串,当JS代码检索数据时,它将显示在页面上,而不是在HTML中。

最新更新