如何下载延迟加载的页面?

时间:2019-04-21 20:13:48

标签: python web-scraping urllib

我需要下载整个页面并进行分析,但是它会使用帮助JavaScript创建一些元素。当我尝试在 urllib 帮助下执行此操作时,我收到了一个HTML页面,其中没有使用JavaScript的元素。我该如何解决这个问题?

import urllib.request as urlib

page = urlib.urlopen('https://www.example.com')
soup = BeautifulSoup(page, 'html5lib')
...

尝试:

colordiv = soup.select("div.pswp__item:nth-child(1) > div:nth-child(1) > img:nth-child(1)'")[0]

使用:

https://www.electrictobacconist.com/smok-nord-p5831

2 个答案:

答案 0 :(得分:1)

即使页面是使用JavaScript呈现的,数据也是通过后台的ajax响应接收的。您要做的就是发出请求。

import requests
import re
url='https://www.electrictobacconist.com/smok-nord-p5831'
#get 5831
product_id=re.findall(r'\d+', url)[-1]
r=requests.get("https://www.electrictobacconist.com/ajax/get_product_options/{}".format(product_id))
print([x['value'] for x in r.json()['attributes'][0]['values']])

输出:

['Black/Blue', 'Black/White', 'Bottle Green', 'Full Black', 'Prism Gold', 'Prism Rainbow', 'Red', 'Resin Rainbow', 'Yellow/Purple', 'Blue/Brown', 'Red/Yellow', 'Red/Green', 'Black/White Resin']

答案 1 :(得分:0)

您可以使用开发工具找到用于更新颜色值的请求

import requests

r = requests.get('https://www.electrictobacconist.com/ajax/get_product_options/5831').json()
colours = [item['value'] for item in r['attributes'][0]['values']]
print(colours)

enter image description here

相关问题