python爬虫爬取ajax页面

本文介绍了一种利用PhantomJS静默浏览器爬取百度贴吧页面的方法,并实现了自动下载图片的功能。代码中详细展示了如何设置PhantomJS驱动、加载页面、获取页面源码及图片链接,并保存图片。
部署运行你感兴趣的模型镜像
# coding:utf-8
# 引入selenium中的webdriver
import re
from urllib import urlretrieve
from selenium import webdriver
import time
# webdriver中的PhantomJS方法可以打开一个我们下载的静默浏览器。
# 输入executable_path为当前文件夹下的phantomjs.exe以启动浏览器

driver = webdriver.PhantomJS(executable_path="C:/Users/lance/Downloads/phantomjs-2.1.1-windows/bin/phantomjs")


# 下载HTML
def getHtml(url):
    # 使用浏览器请求页面
    driver.get(url)
    # 加载3秒,等待所有数据加载完毕
    time.sleep(15)
    # 通过id来定位元素,
    # .text获取元素的文本数据
    html = driver.page_source.encode('utf-8', 'ignore')  # 这个函数获取页面的html
    driver.get_screenshot_as_file(url+".png")  # 获取页面截图
    print "Success To Create the screenshot & gather html"
    # 关闭浏览器

    return html



# 从html中解析出图片URL
def getImgList(html):
       reg = r'src="(http://imgsrc.baidu.com/.*?\.jpg)"'
       imgre = re.compile(reg)
       htmld = html.decode('utf-8')
       imglist = imgre.findall(htmld)
       return imglist

# 下载处理
def imgDownload(imglist,i):
   x=0
   for imgurl in imglist:
       print(imgurl)
       urlretrieve(imgurl,'E:/spider/beautiful/%s%s.jpg' % (x,i))
       x+=1


url = 'http://tieba.baidu.com/p/2173159072#!/l/p'
if __name__ == '__main__':
    for i in range(1,7):
       setUrl = url+str(i)
       print(setUrl)
       html = getHtml(setUrl)

       imgList = getImgList(html)
       print imgList
       imgDownload(imgList,str(i))
driver.close()

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值