【问题标题】:How to __scrape__ data off page loaded via Javascript如何从通过 Javascript 加载的页面上刮取数据
【发布时间】:2020-11-12 07:36:37
【问题描述】:

我想使用 beautifulsoup 从这个页面上刮掉 cmets - https://www.x....s.com/video_id/the-suburl

cmets 在点击时通过 Javascript 加载。 cmets 是分页的,每个页面也会在点击时加载 cmets。我希望获取所有 cmets,对于每个评论,我想获取海报个人资料 url,评论,否。喜欢的次数、不喜欢的次数和发布时间(如页面所述)。

cmets 可以是字典列表。

我该怎么做?

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    此脚本将打印页面上找到的所有 cmets:

    import json
    import requests
    from bs4 import BeautifulSoup
    
    
    url = 'https://www.x......com/video_id/gggjggjj/'
    video_id = url.rsplit('/', maxsplit=2)[-2].replace('video', '')
    
    u = 'https://www.x......com/threads/video/ggggjggl/{video_id}/0/0'.format(video_id=video_id)
    comments = requests.post(u, data={'load_all':1}).json()
    
    for id_ in comments['posts']['ids']:
        print(comments['posts']['posts'][id_]['date'])
        print(comments['posts']['posts'][id_]['name'])
        print(comments['posts']['posts'][id_]['url'])
        print(BeautifulSoup(comments['posts']['posts'][id_]['message'], 'html.parser').get_text())
        # ...etc.
        print('-'*80)
    

    【讨论】:

    【解决方案2】:

    这将通过 Selenium 完成。 Selenium 模拟浏览器。根据您的喜好,您可以使用 chrome 驱动程序或 Firefox 驱动程序,即 geckodriver。

    这里是如何安装 chrome webdriver 的链接: http://jonathansoma.com/lede/foundations-2018/classes/selenium/selenium-windows-install/

    那么在您的代码中,您将如何设置它:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    # this part may change depending on where you installed the webdriver. 
    # You may have to define the path to the driver. 
    # For me my driver is in C:/bin so I do not need to define the path
    chrome_options = Options()
    
    # or '-start maximized' if you want the browser window to open
    chrome_options.add_argument('--headless') 
    
    driver = webdriver.Chrome(options=chrome_options)
    
    driver.get(your_url)
    html = driver.page_source # downloads the html from the driver
    

    Selenium 有几个函数可以用来执行某些操作,例如点击页面上的元素。一旦你找到一个带有 selenium 的元素,你就可以使用 .click() 方法与元素交互。 让我知道这是否有帮助

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2022-12-10
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2011-06-16
      相关资源
      最近更新 更多