4.2-python爬虫之动态网页数据爬取

系列文章目录

python爬虫目录



前言

摘录自B站对应课程笔记
不愧是清华大佬!把Python网络爬虫讲得如此简单明了!从入门到精通保姆级教程(建议收藏)

以下是本篇文章正文内容,下面案例可供参考


一、什么是AJAX

AJAX(Asynchronouse JavaScript And XML)异步JavaScript和XML。过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用Ajax)如果需要更新内容,必须重载整个网页页面。因为传统的在传输数据格式方面,使用的是XML语法。因此叫做AJAX,其实现在数据交互基本上都是使用JSON。使用AJAX加载的数据,即使使用了JS,将数据渲染到了浏览器中,在右键->查看网页源代码还是不能看到通过ajax加载的数据,只能看到使用这个url加载的html代码。

二、获取ajax数据的方式

  1. 直接分析ajax调用的接口。然后通过代码请求这个接口。
  2. 使用Selenium+chromedriver模拟浏览器行为获取数据。 (英[səˈliːniəm] 硒(化学元素,用于制造电气设备和有色玻璃,人体缺此元素可致抑郁等病))
方式优点缺点
分析接口直接可以请求到数据。不需要做一些解析工作。代码量少,性能高。分析接口比较复杂,特别是一些通过js混淆的接口,要有一定的js功底。容易被发现是爬虫。
selenium直接模拟浏览器的行为。浏览器能请求到的,使用selenium也能请求到。爬虫更稳定。代码量多。性能低。

三、Selenium+chromedriver获取动态数据

Selenium相当于是一个机器人。可以模拟人类在浏览器上的一些行为,自动处理浏览器上的一些行为,比如点击,填充数据,删除cookie等。chromedriver是一个驱动Chrome浏览器的驱动程序,使用他才可以驱动浏览器。当然针对不同的浏览器有不同的driver。以下列出了不同浏览器及其对应的driver:
Chrome
https://sites.google.com/a/chromium.org/chromedriver/downloads
http://npm.taobao.org/mirrors/chromedriver/
Firefoxhttps://github.com/mozilla/geckodriver/releases
Edgehttps://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Safarihttps://webkit.org/blog/6900/webdriver-support-in-safari-10/

四、安装Selenium和chromedriver

1、安装Selenium:Selenium有很多语言的版本,有java、ruby、python等。我们下载python版本的就可以了。

pip install selenium

2、安装chromedriver:下载完成后,放到不需要权限的纯英文目录下就可以了。

五、快速入门

现在以一个简单的获取百度首页的例子来讲下Selenium和chromedriver如何快速入门:

from selenium import webdriver
 
# chromedriver.exe 的绝对路径
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
 
# 初始化一个driver, 并且指定 chromedriver 的路径
driver = webdriver.Chrome(executable_path=driver_path)
 
# 请求网页
driver.get("https://www.baidu.com")
 
# 通过 page_source 获取网页源代码
print(driver.page_source)

六、selenium常用操作

selenium文档:http://selenium-python.readthedocs.io/installation.html#introduction

1、关闭页面

driver.close():关闭当前页面。
driver.quit():退出整个浏览器。

2、定位元素

使用 driver.find_element() 需要导入 By :

from selenium.webdriver.common.by import By
  1. find_element_by_id:根据id来查找某个元素。等价于:
 submitTag = driver.find_element_by_id('su')
 submitTag1 = driver.find_element(By.ID,'su')
  1. find_element_by_class_name:根据类名查找元素。 等价于:
 submitTag = driver.find_element_by_class_name('su')
 submitTag1 = driver.find_element(By.CLASS_NAME,'su')
  1. find_element_by_name:根据name属性的值来查找元素。等价于:
 submitTag = driver.find_element_by_name('email')
 submitTag1 = driver.find_element(By.NAME,'email')
  1. find_element_by_tag_name:根据标签名来查找元素。等价于:
 submitTag = driver.find_element_by_tag_name('div')
 submitTag1 = driver.find_element(By.TAG_NAME,'div')
  1. find_element_by_xpath:根据xpath语法来获取元素。等价于:
 submitTag = driver.find_element_by_xpath('//div')
 submitTag1 = driver.find_element(By.XPATH,'//div')
  1. find_element_by_css_selector:根据css选择器选择元素。等价于:
 submitTag = driver.find_element_by_css_selector('//div')
 submitTag1 = driver.find_element(By.CSS_SELECTOR,'//div')

要注意,find_element是获取第一个满足条件的元素。find_elements是获取所有满足条件的元素。

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com")
 
# inputTag = driver.find_element_by_id("kw")
# inputTag = driver.find_element(By.ID, "kw")
 
# inputTag = driver.find_element_by_name("wd")
# inputTag = driver.find_element(By.NAME, "wd")
 
# inputTag = driver.find_element_by_class_name("s_ipt")
# inputTag = driver.find_element(By.CLASS_NAME, "s_ipt")
 
# inputTag = driver.find_element_by_tag_name("input")
# inputTag = driver.find_element(By.TAG_NAME, "input")
 
# inputTag = driver.find_element_by_xpath("//input[@id='kw']")
# inputTag = driver.find_element(By.XPATH, "//input[@id='kw']")
 
# inputTag = driver.find_element_by_css_selector(".quickdelete-wrap > input")
inputTag = driver.find_element(By.CSS_SELECTOR, ".quickdelete-wrap > input")
 
inputTag.send_keys("python")

总结:

  1. 如果只想要解析网页中的数据,那么推荐将网页源代码仍给 lxml 来解析。因为 lxml 底层使用的是 C 语言,所以解析效率会更高。
  2. 如果想要对元素进行一些操作,比如给一个文本框输入值,或者是点击某个按钮,那么就必须使用 seleniem 给我们提供的查找元素的方法。

3、 操作表单元素

#常见的表单元素
    input type='text/ password/ email/ number'
    button input[type='submit']
    checkbox input='checkbox'
    select 下拉列表
  1. 操作输入框:分为两步。第一步:找到这个元素。第二步:使用send_keys(value),将数据填充进去。示例代码如下:
 inputTag = driver.find_element_by_id('kw')
 inputTag.send_keys('python')
 #使用clear方法可以清除输入框中的内容
 inputTag.clear()
  1. 操作checkbox:因为要选中checkbox标签,在网页中是通过鼠标点击的。因此想要选中checkbox标签,那么先选中这个标签,然后执行click事件。示例代码如下:
 rememberTag = driver.find_element_by_name("rememberMe")
 rememberTag.click()
  1. 选择select:select元素不能直接点击。因为点击后还需要选中元素。这时候selenium就专门为select标签提供了一个类selenium.webdriver.support.ui.Select。将获取到的元素当成参数传到这个类中,创建这个对象。以后就可以使用这个对象进行选择了。示例代码如下:
 from selenium.webdriver.support.ui import Select
 # 选中这个标签,然后使用Select创建对象
 selectTag = Select(driver.find_element_by_name("jumpMenu"))
 # 根据索引选择
 selectTag.select_by_index(1)
 # 根据值选择
 selectTag.select_by_value("http://www.95yueba.com")
 # 根据可视的文本选择
 selectTag.select_by_visible_text("95秀客户端")
 # 取消选中所有选项
 selectTag.deselect_all()
  1. 操作按钮:操作按钮有很多种方式。比如单击、右击、双击等。这里讲一个最常用的。就是点击。直接调用click函数就可以了。示例代码如下:
 inputTag = driver.find_element_by_id('su')
 inputTag.click()

4、行为链

有时候在页面中的操作可能要有很多步,那么这时候可以使用鼠标行为链类ActionChains来完成。比如现在要将鼠标移动到某个元素上并执行点击事件。那么示例代码如下:

import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com")
 
# 测试行为链
inputTag = driver.find_element_by_id("kw")
submitBt = driver.find_element_by_id("su")
 
action = ActionChains(driver)  #创建 ActionChaions
action.move_to_element(inputTag)
action.send_keys_to_element(inputTag, "python")
action.move_to_element(submitBt)
action.click(submitBt)
action.perform()  # 执行所有行为

还有更多的鼠标相关的操作。

click_and_hold(element):点击但不松开鼠标。
context_click(element):右键点击。
double_click(element):双击。
更多方法请参考:http://selenium-python.readthedocs.io/api.html

5、Cookie操作

#1. 获取所有的cookie:
 for cookie in driver.get_cookies():
     print(cookie)
#2. 根据cookie的key获取value:
 value = driver.get_cookie(key)
#3. 删除所有的cookie:
 driver.delete_all_cookies()
#4. 删除某个cookie:
 driver.delete_cookie(key)
from selenium import webdriver
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com")
 
# 查看所有
for cookie in driver.get_cookies():
    print(cookie)
 
print("查询某个 cookie" + "* " * 20)
# 查询某个 cookie
print(driver.get_cookie("BAIDUID"))
 
print("删除某个cookie " + "* " * 20)
# 删除某个 cookie
driver.delete_cookie("BAIDUID")
print(driver.get_cookie("BAIDUID"))
 
print("删除所有cookie " + "* " * 20)
driver.delete_all_cookies()

6、页面等待

现在的网页越来越多采用了 Ajax 技术,这样程序便不能确定何时某个元素完全加载出来了。如果实际页面等待时间过长导致某个dom元素还没出来,但是你的代码直接使用了这个WebElement,那么就会抛出NullPointer的异常。为了解决这个问题。所以 Selenium 提供了两种等待方式:一种是隐式等待、一种是显式等待。

  1. 隐式等待:调用driver.implicitly_wait。那么在获取不可用的元素之前,会先等待10秒中的时间。示例代码如下:
from selenium import webdriver
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
# 隐式等待
driver.implicitly_wait(10)
driver.get("https://www.baidu.com")
 
driver.find_element_by_id("123")
  1. 显式等待:显式等待是表明某个条件成立后才执行获取元素的操作。也可以在等待的时候指定一个最大的时间,如果超过这个时间那么就抛出一个异常。显式等待应该使用selenium.webdriver.support.excepted_conditions期望的条件和selenium.webdriver.support.ui.WebDriverWait来配合完成。示例代码如下:
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
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com")
# 显式等待
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.ID, "123"))
    )
finally:
    print("退出浏览器")
    driver.quit()
  1. 一些其他的等待条件:
    presence_of_element_located:某个元素已经加载完毕了。
    presence_of_all_emement_located:网页中所有满足条件的元素都加载完毕了。
    element_to_be_cliable:某个元素是可以点击了。
    更多条件请参考:http://selenium-python.readthedocs.io/waits.html

7、切换页面

有时候窗口中有很多子tab页面。这时候肯定是需要进行切换的。selenium提供了一个叫做switch_to_window来进行切换,具体切换到哪个页面,可以从driver.window_handles中找到。示例代码如下:

from selenium import webdriver
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com/")
 
# 打开一个新窗口
driver.execute_script("window.open('https://douban.com/')")
# 切换到新打开的页面
# driver.switch_to_window(driver.window_handles[1])  # 已经废弃
driver.switch_to.window(driver.window_handles[1])
 
print(driver.current_url)
# print(driver.page_source)

注意:
虽然在 Chrome 窗口中显示的是新页面,但是 driver 中还没切换,
如果想要在代码中切换到新的页面,并且做一些爬虫,
那么应该使用 switch_to.window 来说切换到指定的窗口。
driver.window_handlers 是一个列表,里面装的都是窗口句柄。
他会按照打开页面的顺序来存储窗口的句柄。

8、设置代理ip

有时候频繁爬取一些网页。服务器发现你是爬虫后会封掉你的ip地址。这时候我们可以更改代理ip。更改代理ip,不同的浏览器有不同的实现方式。这里以Chrome浏览器为例来讲解:

from selenium import webdriver
 
driver_path = r"D:\chromedriver_win32\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument("--proxy-server=http//114.101.250.113:9999")
 
driver = webdriver.Chrome(executable_path=driver_path, options=options)
 
driver.get("http://httpbin.org/ip")

9、WebElement元素

from selenium.webdriver.remote.webelement import WebElement类是每个获取出来的元素的所属类。

常用的属性:

get_attribute:这个标签的某个属性的值。
screentshot:获取当前页面的截图。这个方法只能在driver上使用。driver的对象类,也是继承自WebElement。

七、通过 selenium 爬取 拉钩 网页面

request + xpath 版本

import requests, time, re
from lxml import etree
 
# Cookie 的过期时间比较短,需要重新复制后放进去
headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
    "Referer": "https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=",
    "Origin": "https://www.lagou.com",
    "x-anit-forge-code": "0",
    "x-anit-forge-token": "None",
    "x-requested-with": "XMLHttpRequest",
    "Cookie": "xxxx"
}
 
def parse_detail_page(url, cookies):
    # 获取职位详细信息页面数据
    response = requests.get(url=url, headers=headers, cookies=cookies)
    text = response.content.decode("utf-8")
    html = etree.HTML(text)
    p_name = html.xpath("//span[@class='position-head-wrap-name']/text()")[0]
    job_request_spans = html.xpath("//dd[@class='job_request']//span")
    p_salary = job_request_spans[0].xpath(".//text()")[0]
    p_city = job_request_spans[1].xpath(".//text()")[0]
    p_city = re.sub(r"[\s/]", "", p_city)
    p_years = job_request_spans[2].xpath(".//text()")[0]
    p_years = re.sub(r"[\s/]", "", p_years)
    p_education = job_request_spans[3].xpath(".//text()")[0]
    p_education = re.sub(r"[\s/]", "", p_education)
    p_detail = "".join(html.xpath("//dd[@class='job_bt']//text()")).strip()
    p_info = {
        "p_name": p_name,
        "p_salary": p_salary,
        "p_city": p_city,
        "p_years": p_years,
        "p_education": p_education,
        "p_detail": p_detail,
    }
    print(p_info)
    print("* " * 20)
    return p_info
 
def main():
    all_position = []
    url = "https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false"
    # 这个例子只爬取前五页内容
    for i in range(5):
        print("* " * 10 + "开始获取第 {} 页面".format(i))
        # 拼接请求的数据
        data = {
            "first": "false",
            "pn": "{}".format(i),
            "kd": "python"
        }
        # 获取职位信息
        response = requests.post(url=url, headers= headers, data=data)
        # 获取职位信息
        positions = response.json()["content"]["positionResult"]["result"]
        time.sleep(1)
        # 获取职位id,id是请求数据url的构成部分
        for position in positions:
            positionId = position["positionId"]
            position_url = "https://www.lagou.com/jobs/{}.html".format(positionId)
            cookies = response.cookies
            p = parse_detail_page(position_url, cookies)
            time.sleep(1)
            all_position.append(p)
    print(all_position)
 
 
if __name__ == '__main__':
    main()
"""
遇到问题
    请求第一页的第一条连接之后,后面被识别出来是爬虫,第二条详情就请求不到了        
"""

selenium 版本

import re, time
from selenium import webdriver
from lxml import etree
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as  EC
from selenium.webdriver.common.by import By
 
 
class LagouSpider(object):
 
    driver_path = r"D:\chromedriver_win32\chromedriver.exe"
 
    def __init__(self):
        self.driver = webdriver.Chrome(executable_path=LagouSpider.driver_path)
        self.url = "https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput="
 
    def run(self):
        self.driver.get(self.url)  # 请求页面
        while True:
            source = self.driver.page_source  # 获取html页面数据
            self.parse_list_page(source)  # 解析职位列表页面
            time.sleep(1)
            # 等待 xpath 寻找的元素出现,否则 10 s 抛出异常
            # 如果没有这一句,页面下一页的按钮可能还没加载出来,获取不到
            WebDriverWait(driver=self.driver,timeout=10).until(
                EC.presence_of_all_elements_located((By.XPATH, "//div[@class='pager_container']/span[last()]"))
            )
            nextBtn = self.driver.find_element_by_xpath("//div[@class='pager_container']/span[last()]")
            print(nextBtn.get_attribute("class"))
            if "pager_next_disabled" in nextBtn.get_attribute("class"):
                print("已经到最后一页退出")
                break
            print("进入下一页")
            nextBtn.click()  # 这个需要放在 get_attribute 之后,否则点击之后会找不到,报错
 
 
    def parse_list_page(self, source):
        html = etree.HTML(source)
        hrefs = html.xpath("//a[@class='position_link']/@href")
        for href in hrefs:
            self.request_detail_page(href)
            time.sleep(1)
 
    def request_detail_page(self, url):
        self.driver.execute_script("window.open('{}')".format(url))
        self.driver.switch_to.window(self.driver.window_handles[1])  # 切换到新打开的职位详情页
        source = self.driver.page_source  # 获取详情页面 html
        self.parse_detail_page(source)  # 解析 html
        self.driver.close()  # 关闭当前详情页面
        self.driver.switch_to.window(self.driver.window_handles[0])  # 切换回到职位列表页面
 
    def parse_detail_page(self, source):
        html = etree.HTML(source)
        p_name = html.xpath("//span[@class='position-head-wrap-name']/text()")[0]
        job_request_spans = html.xpath("//dd[@class='job_request']//span")
        p_salary = job_request_spans[0].xpath(".//text()")[0]
        p_city = job_request_spans[1].xpath(".//text()")[0]
        p_city = re.sub(r"[\s/]", "", p_city)
        p_years = job_request_spans[2].xpath(".//text()")[0]
        p_years = re.sub(r"[\s/]", "", p_years)
        p_education = job_request_spans[3].xpath(".//text()")[0]
        p_education = re.sub(r"[\s/]", "", p_education)
        p_detail = "".join(html.xpath("//dd[@class='job_bt']//text()")).strip()
        p_info = {
            "p_name": p_name,
            "p_salary": p_salary,
            "p_city": p_city,
            "p_years": p_years,
            "p_education": p_education,
            "p_detail": p_detail,
        }
        print(p_info)
        print("* " * 20)
        return p_info
 
 
if __name__ == '__main__':
    spider = LagouSpider()
    spider.run()
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nosimper

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值