Python爬虫(6)-抓动态html

环境:Python3.6
工具:PyCharm
目录:Menu
目标:1.抓取Ajax执行后的动态html数据。2.抓取网页重定向后html数据。

1.抓取Ajax执行后的动态HTML

例子:抓取煎蛋网的妹子图片

1.直接抓取

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://jandan.net/ooxx")
bsObj = BeautifulSoup(html.read(),"lxml")
print(bsObj)

在输出的内容中,找到目标图片,发现是以下格式,抓不到真实数据。

<p>
  <img onload="jandan_load_img(this)" src="//img.jandan.net/img/blank.gif" />
  <span class="img-hash">Ly93dzMuc2luYWltZy5jbi9tdzEwMjQvMDA3M3RMUEdneTFmeDk5NTl2eDQyZzMwNmYwNWtxdjcuZ2lm</span>
</p>

为什么抓不到真实数据?
图片标签执行了一段JavaScript代码"jandan_load_img(this)",然后又动态增删了一些元素。
可以查看源码,"jandan_load_img(this)",从img-hash里解密出了图片真实的地址。

2.在python中用Selenium执行JavaScript

0. 工具:先安装PhantomJS(这是一个非python库,不能使用pip安装),再使用pip安装Selenium

phantomJS是一个"无头"(headless)浏览器。它会把网站加载到内存上并执行页面上的JavaScript,但是它不会向用户展示网页的图形界面。
Selenium可以让浏览器自动加载页面,获取所需的数据,或者判断网站上某些动作是否发生。

1. 基础版:webdriver使用强制等待的方式,等待javaScript执行完毕
from selenium import webdriver
import time
from bs4 import BeautifulSoup

#如果报错,可以带上phantomjs的执行路径。
#webdriver.PhantomJS(executable_path="")
driver = webdriver.PhantomJS()
driver.get("http://jandan.net/ooxx")
#这里休眠3s,是为了等待页面js加载并运行完毕。如果网速慢,可以把这个时间延长点
time.sleep(3)
pageSource = driver.page_source
bsObj = BeautifulSoup(pageSource, "lxml")
print(bsObj)
driver.close()

在输入的内容中,可以找到目标图片的真实地址

<p>
  <a class="view_img_link" href="//ww3.sinaimg.cn/large/006XNEY7gy1fxaax6f3sbj30hs0bvjsz.jpg" target="_blank">[查看原图]</a><br/>
  <img src="http://ww3.sinaimg.cn/mw600/006XNEY7gy1fxaax6f3sbj30hs0bvjsz.jpg" style="max-width: 480px; max-height: 750px;"/>
</p>
2. 改进版:WebDriverWait + until 构成隐式等待
WebDriverWait(driver, timeout, poll_frequency: float=POLL_FREQUENCY, ignored_exceptions=None)
# driver: 传入WebDriver实例,即我们上例中的driver
# timeout: 超时时间,等待的最长时间(同时要考虑隐性等待时间)
# poll_frequency: 调用until或until_not中的方法的间隔时间,默认是0.5秒
# ignored_exceptions: 忽略的异常,如果在调用until或until_not的过程中抛出这个元组中的异常, 则不中断代码,继续等待;
# 如果抛出的是这个元组外的异常,则中断代码,抛出异常。默认只有NoSuchElementException。
until(self, method, message)
until_not(self, method, message)
# until是当某元素出现或什么条件成立则继续执行,until_not是当某元素消失或什么条件不成立则继续执行。
# method: 在等待期间,每隔一段时间调用这个传入的方法,直到返回值不是False
# message: 如果超时,抛出TimeoutException,将message传入异常

expected_conditions


image.png
expected_conditions.visibility_of_element_located(self, locator)
# locator 定位器,它是一种抽象的查询语言, 用By对象进行选择。
(By.ID, "id名字")
(By.CLASS_NAME, "class名字")
# XPATH表达式选择匹配的元素。很复杂的查询语言。
image.png

开始抓取

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import  WebDriverWait
from selenium.webdriver.support import expected_conditions as EC 
from bs4 import BeautifulSoup

driver = webdriver.PhantomJS()
driver.get("http://jandan.net/ooxx")
try:
    element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "commentlist")))
except:
    print("element can not find")
finally:
    pageSource = driver.page_source
    bsObj = BeautifulSoup(pageSource, "lxml")
    print(bsObj)
    driver.close()

在输入的内容中,可以找到目标图片的真实地址

<p style="position: relative;">
  <a class="view_img_link" href="//ww3.sinaimg.cn/large/006XNEY7gy1fxat8kz0hhg30a00ho7wj.gif" target="_blank">[查看原图]</a><br/>
  <img org_src="http://ww3.sinaimg.cn/mw1024/006XNEY7gy1fxat8kz0hhg30a00ho7wj.gif" src="http://ww3.sinaimg.cn/thumb180/006XNEY7gy1fxat8kz0hhg30a00ho7wj.gif" style="max-width: 480px; max-height: 750px;"/>
</p>

2.抓取网页重定向后HTML

客户端重定向:在服务器将页面内容发送到浏览器之前,由浏览器执行JavaScript完成页面跳转。需要Selenium执行JavaScript代码
服务端重定向:可以很轻松的用urllib库解决,不需要使用Selenium,只需要抓取返回的HTML即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容