1. Selenium
Selenium 是一个JavaScript框架,调用 webdriver 模拟在浏览器内的操作,可以适用 Chrome、 Firefox 、IE 等浏览器。
本文用的是 PhantomJS,一个在可以后台运行的无头浏览器(Scriptable Headless Browser)。
- PhantomJS 项目目前已经暂停更新。
 
- Selenium 推荐用 Chrome 或 Firefox 的无头模式。
 
- 但 chromedriver 无头模式启动时,还是会有一个空白的命令行窗口,比较讨厌,因此还是用 PhantomJS。
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | import time
  from bs4 import BeautifulSoup from selenium import webdriver
 
 
 
 
 
 
 
 
 
 
 
 
  phantomjs_path = r'C:\xxx\scoop\apps\PhantomJS\current\phantomjs' driver = webdriver.PhantomJS(executable_path=phantomjs_path)
  driver.get('https://www.baidu.com') time.sleep(1)
  print(driver.title) print(driver.page_source)
  driver.close() driver.quit()
   | 
 
2. BeautifulSoup
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
   | driver.get(url)
  content = driver.page_source soup = BeautifulSoup(content, 'html.parser')  
 
  div = soup.find('div', {'class': 'title'})
 
  div = soup.find('div', {'class': ['title', ' ']})
 
  title = div.a.get('title')
 
  text = div.a.text
 
  sound_list = soup.find_all('div', {'class': ['sound', ' ']}) for sound in sound_list:     print(sound)
 
  div = soup.find('div', {'class': ['title', ' '], 'id': 'sound'})
   | 
 
3. Selenium 模拟浏览器翻页 (滚动条)
1 2 3 4 5 6 7 8 9
   |  driver.get(url)
  page_num = 10 for i in range(page_num):     driver.execute_script('window.scrollBy(0, document.body.scrollHeight)')     time.sleep(3)
  content = driver.page_source
 
  |