【问题标题】:How to download a page with lazy loading?如何下载延迟加载的页面?
【发布时间】:2019-09-11 04:10:02
【问题描述】:

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

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

【问题讨论】:

  • 您能否附上网址并准确说明您的目标是什么?
  • link 选择颜色colordiv = soup.select("div.pswp__item:nth-child(1) > div:nth-child(1) > img:nth-child(1)'")[0]
  • 使用硒...

标签: python web-scraping urllib


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    即使页面是使用 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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2019-11-22
      相关资源
      最近更新 更多