【问题标题】:How to scrape dynamic content with BS4 or Selenium (Python)?如何使用 BS4 或 Selenium (Python) 抓取动态内容?
【发布时间】:2017-10-04 23:03:22
【问题描述】:

我正在尝试从文件查找器页面 (example) 抓取 Github 存储库中的所有文件路径。

Beautiful Soup 4 未能抓取包含文件路径列表的 <tbody class="js-tree-finder-results js-navigation-container js-active-navigation-container"> 元素。我认为这是 b/c bs4 无法抓取动态内容,所以我尝试等待所有元素加载 Selenium:

driver = webdriver.PhantomJS()
driver.get("https://github.com/chrisspen/weka/find/master")

# Explicitly wait for the element to become present
wait = WebDriverWait(driver, 10)
element = wait.until(
    EC.presence_of_element_located((
        By.CSS_SELECTOR, "js-tree-finder-results.js-navigation-container.js-active-navigation-container"
    ))
)

# Pass the found element into the script
items = driver.execute_script('return arguments[0].innerHTML;', element)
print(items)

但它仍然无法找到元素。

我做错了什么?

附言

可以通过 JS 控制台使用以下脚本轻松获取文件路径:

window.onload = function() {
    var fileLinks = document.getElementsByClassName("css-truncate-target js-navigation-open js-tree-finder-path"); 
    var files = []; 
    for (var i = 0; i < fileLinks.length; i++) { 
        files.push(fileLinks[i].innerHTML); 
    } 
    return files; 
}

编辑:

我的程序需要使用无头浏览器,例如 PhantomJS。

【问题讨论】:

  • Selenium 不支持多个类名。如果一个类包含空格,它将被视为复合选择器,由 By.CSS_SELECTOR 选择。

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

由于 Github 的 Content-Security-Policy 设置,当前版本的 PhantomJS 无法捕获 Github 内容。这是一个已知的错误并记录在 here。根据那个问题页面,降级到 PhantomJS 版本 1.9.8 是解决问题的一种方法。

另一种解决方案是使用 chromedriver:

driver = webdriver.Chrome('chromedriver')
driver.get("https://github.com/chrisspen/weka/find/master")

wait = WebDriverWait(driver, 10)

element = wait.until(
     EC.presence_of_element_located((
        By.CLASS_NAME, "js-tree-finder-path"
     ))
)

【讨论】:

  • 嗯,使用 Chrome 驱动程序仍然会产生 TimeoutException——它无法找到元素。在 macOS Sierra 上使用 PhantomJS 1.9.8 总是会出现段错误,这是一个已知且未解决的issue
猜你喜欢
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 2021-04-28
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多