從零開始學Python——使用Selenium抓取動態網頁數據

1.selenium抓取動態網頁數據基礎介紹

1.1 什麼是AJAX

  AJAX(Asynchronouse JavaScript And XML:異步JavaScript和XML)通過在後臺與服務器進行少量數據交換,Ajax 可以使網頁實現異步更新,這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行局部更新。傳統的網頁(不使用Ajax)如果需要更新內容,必須重載整個網頁頁面。

  因爲傳統的網頁在傳輸數據格式方面,使用的是XML語法,因此叫做AJAX,其實現在數據交互基本上都是使用JSON。使用AJAX加載的數據,即使使用了JS將數據渲染到了瀏覽器中,在右鍵->查看網頁源代碼還是不能看到通過ajax加載的數據,只能看到使用這個url加載的html代碼。

1.2 獲取ajax數據的方式

  法1:直接分析ajax調用的接口。然後通過代碼請求這個接口。

  法2:使用Selenium+chromedriver模擬瀏覽器行爲獲取數據。

方式

優點

缺點

分析接口

直接可以請求到數據。不需要做一些解析工作。代碼量少,性能高。

分析接口比較複雜,特別是一些通過js混淆的接口,要有一定的js功底。容易被發現是爬蟲。

selenium

直接模擬瀏覽器的行爲。瀏覽器能請求到的,使用selenium也能請求到。爬蟲更穩定。

代碼量多。性能低。

1.3 Selenium+chromedriver獲取動態數據

  Selenium相當於是一個機器人。可以模擬人類在瀏覽器上的一些行爲,自動處理瀏覽器上的一些行爲,比如點擊,填充數據,刪除cookie等。chromedriver是一個驅動Chrome瀏覽器的驅動程序,使用他纔可以驅動瀏覽器。當然針對不同的瀏覽器有不同的driver。以下列出了不同瀏覽器及其對應的driver:

  1. Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
  2. Firefox:https://github.com/mozilla/geckodriver/releases
  3. Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
  4. Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/

1.4 安裝Selenium和chromedriver

  1. 安裝SeleniumSelenium有很多語言的版本,有java、ruby、python等。我們下載python版本的就可以了。
  2. pip install selenium
  3. 安裝chromedriver:下載完成後,放到不需要權限的純英文目錄下就可以了。

1.5 快速入門

  現在以一個簡單的獲取百度首頁的例子來講下Seleniumchromedriver如何快速入門:

from selenium import webdriver


# chromedriver的絕對路徑
driver_path = r'D:\ProgramApp\chromedriver\chromedriver.exe'


# 初始化一個driver,並且指定chromedriver的路徑
driver = webdriver.Chrome(executable_path=driver_path)
# 請求網頁
driver.get("https://www.baidu.com/")
# 通過page_source獲取網頁源代碼
print(driver.page_source)

1.6 selenium常用操作

參考:Selenium的使用

1.7 爬取拉鉤網職位信息

直接直接分析ajax調用的接口爬取

import requests
from lxml import etree
import time
import re




headers = {
    "Accept":"application/json, text/javascript, */*; q=0.01",
    "Accept-Encoding":"gzip, deflate, br",
    "Accept-Language":"zh-CN,zh;q=0.9",
    "Connection":"keep-alive",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
    "Referer":"https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=",
    "Origin":"https://www.lagou.com",
    "Host":"www.lagou.com",
    "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie":"_ga=GA1.2.1602115737.1553064534; user_trace_token=20190320144853-39b1375a-4adc-11e9-a253-525400f775ce; LGUID=20190320144853-39b13f88-4adc-11e9-a253-525400f775ce; WEBTJ-ID=20190408120043-169fb1afd63488-06179b118ca307-7a1437-2073600-169fb1afd648ed; _gid=GA1.2.1826141825.1554696044; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22169fb1bb2c41ea-04951e55adc96a-7a1437-2073600-169fb1bb2c58d0%22%2C%22%24device_id%22%3A%22169fb1bb2c41ea-04951e55adc96a-7a1437-2073600-169fb1bb2c58d0%22%7D; sajssdk_2015_cross_new_user=1; _putrc=4C5D2603888320CA; JSESSIONID=ABAAABAAADEAAFIB00F5DDE71D51610901CB9E0031812BA; login=true; unick=%E4%BC%8D%E6%99%93%E4%B8%BD; showExpriedIndex=1; showExpriedCompanyHome=1; showExpriedMyPublish=1; hasDeliver=49; gate_login_token=7b04a40da89145a1fbc90a3d719616d28c8b0a303344ac37; index_location_city=%E6%88%90%E9%83%BD; X_MIDDLE_TOKEN=1221e6b5040722dc86f5ceb557e11965; _gat=1; LGSID=20190408151935-a9976fbf-59ce-11e9-8cc8-5254005c3644; PRE_UTM=m_cf_cpc_baidu_pc; PRE_HOST=www.baidu.com; PRE_SITE=https%3A%2F%2Fwww.baidu.com%2Fbaidu.php%3Fsc.Ks000001qLT2daZnZWIez3ktR_jhHue3tONZubxU9mivhxeuj-Fxrjg6NnVcKTp-GYJ_YRvrc9_yOJ4uV-IEpfnPazPz7ctjve1qlDokCDfHYo9PV0uDfTmN1OunNUcCRU-sJuR8RZz60PAXzfKybAdvuCxUedbt8aWtTjAdCCuO298TwT8zN1-T5EG3kgkOweg0DHGIbvP55IZbr6.DY_NR2Ar5Od663rj6tJQrGvKD7ZZKNfYYmcgpIQC8xxKfYt_U_DY2yP5Qjo4mTT5QX1BsT8rZoG4XL6mEukmryZZjzsLTJplePXO-8zNqrw5Q9tSMj_qTr1x9tqvZul3xg1sSxW9qx-9LdoDkY4QPSl81_4pqO24rM-8dQjPakb3dS5iC0.U1Yk0ZDqs2v4VnL30ZKGm1Yk0Zfqs2v4VnL30A-V5HcsP0KM5gK1n6KdpHdBmy-bIykV0ZKGujYzr0KWpyfqnWcv0AdY5HDsnHIxnH0krNtknjc1g1nsnHNxn1msnfKopHYs0ZFY5HDLn6K-pyfq0AFG5HcsP0KVm1Y3nHDYP1fsrjuxnH0snNtkg1Dsn-ts0Z7spyfqn0Kkmv-b5H00ThIYmyTqn0K9mWYsg100ugFM5H00TZ0qPWm1PHm1rj640A4vTjYsQW0snj0snj0s0AdYTjYs0AwbUL0qn0KzpWYs0Aw-IWdsmsKhIjYs0ZKC5H00ULnqn0KBI1Ykn0K8IjYs0ZPl5fK9TdqGuAnqTZnVUhC0IZN15Hnkn1fknHT4P1DvPHR1PW61P100ThNkIjYkPHRYP10LrHTkPjTY0ZPGujd9rAwBmhuWrj0snjDzrj0Y0AP1UHYsPbm3wWTsrH0srjwarDcz0A7W5HD0TA3qn0KkUgfqn0KkUgnqn0KlIjYs0AdWgvuzUvYqn7tsg1Kxn7ts0Aw9UMNBuNqsUA78pyw15HKxn7tsg1nkrjm4nNts0ZK9I7qhUA7M5H00uAPGujYknjT1P1fkrjcY0ANYpyfqQHD0mgPsmvnqn0KdTA-8mvnqn0KkUymqn0KhmLNY5H00uMGC5H00uh7Y5H00XMK_Ignqn0K9uAu_myTqnfK_uhnqn0KEIjYs0AqzTZfqnanscznsc100mLFW5HRdPj0Y%26word%3D%25E6%258B%2589%25E5%258B%25BE%25E7%25BD%2591%26ck%3D1701.10.72.227.558.354.602.254%26shh%3Dwww.baidu.com%26sht%3D62095104_19_oem_dg%26us%3D1.0.1.0.1.301.0%26bc%3D110101; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2Flp%2Fhtml%2Fcommon.html%3Futm_source%3Dm_cf_cpc_baidu_pc%26m_kw%3Dbaidu_cpc_cd_e110f9_d2162e_%25E6%258B%2589%25E5%258B%25BE%25E7%25BD%2591; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1553064535,1554696044,1554707975; TG-TRACK-CODE=index_search; SEARCH_ID=16b25888bc6f489f981996ef505d6930; X_HTTP_TOKEN=3704e5535eab672a10080745514b2c7fac0430c282; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1554708001; LGRID=20190408152002-b9743b5b-59ce-11e9-9a84-525400f775ce",
    "X-Anit-Forge-Code":"0" ,
    "X-Anit-Forge-Token":'',
    "X-Requested-With":'XMLHttpRequest'
}


def get_detail_page_url():
    datas =[]
    url = 'https://www.lagou.com/jobs/positionAjax.json'
    form_data = {
        "first":"faise",
        "pn":1,
        "kd":"python"
    }
    params = {
        'city':'成都',
        'needAddtionalResult':'false'
    }
    for pn in range(1,14):
        form_data['pn'] = pn
        response = requests.request(method='post',url=url,headers=headers,params = params,data = form_data)
        result = response.json()
        result_list = result['content']['positionResult']['result']
        for position in result_list:
            position_id = position['positionId']
            detail_url = 'https://www.lagou.com/jobs/%s.html'%position_id
            data = parse_detail_page(detail_url)
            datas.append(data)
            time.sleep(2)
    return datas


def parse_detail_page(url):
    resonse = requests.request(method='get',url=url,headers = headers)
    text = resonse.text
    html = etree.fromstring(text,parser=etree.HTMLParser())
    position_name = html.xpath('//span[@class="name"]/text()')[0].strip()
    detail_list = html.xpath('//dd[@class="job_request"]//span')
    salary = detail_list[0].xpath('text()')[0].strip()
    city = detail_list[1].xpath('text()')[0].strip()
    city = re.sub(r'[\s/]','',city)
    work_years = detail_list[2].xpath('text()')[0].strip()
    work_years = re.sub(r'[\s/]','',work_years)
    education = detail_list[3].xpath('text()')[0].strip()
    education = re.sub(r'[\s/]','',education)
    job_details = ''.join(html.xpath('//div[@class="job-detail"]//p//text()'))
    data = {
       "position_name":position_name,
        "salay":salary,
        "city":city,
        "work_years":work_years,
        "education":education,
        "job_details":job_details


    }
    return data






def main():
    datas = get_detail_page_url()
    print(datas)


if __name__ == '__main__':
    main()

selenium結合lxml爬取

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


from lxml import etree
import re
import time


class Lagouspider(object):
    driver_path = r'E:\study\chromedriver\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='
        self.positions = []


    def run(self):
        while True:
            self.driver.get(self.url)
            source = self.driver.page_source
            WebDriverWait(driver=self.driver,timeout=10).until(EC.presence_of_element_located((By.XPATH,'//div[@class="pager_container"]/span[last()]')))
            self.parse_list_page(source)
            next_btn = self.driver.find_element_by_xpath('//div[@class="pager_container"]/span[last()]')
            if "pager_next_disabled"  in next_btn.get_attribute('class'):
                break
            else:
                next_btn.click()
            time.sleep(1)


    def parse_list_page(self,source):
        html = etree.HTML(source)
        links = html.xpath('//a[@class="position_link"]/@href')
        for link in links:
            self.request_detail_page(link)
            time.sleep(1)


    def request_detail_page(self,url):
        self.driver.execute_script("window.open('%s')"%url)
        self.driver.switch_to.window(self.driver.window_handles[1])
        WebDriverWait(self.driver,timeout=10).until(EC.presence_of_element_located((By.XPATH,'//span[@class="name"]')))
        source = self.driver.page_source
        self.parse_detail_page(source)
        #關閉當前詳情頁
        self.driver.close()
        #切換回職位列表頁
        self.driver.switch_to.window(self.driver.window_handles[0])


    def parse_detail_page(self,source):
        html = etree.HTML(source)
        position_name = html.xpath('//span[@class="name"]/text()')[0].strip()
        detail_list = html.xpath('//dd[@class="job_request"]//span')
        salary = detail_list[0].xpath('text()')[0].strip()
        city = detail_list[1].xpath('text()')[0].strip()
        city = re.sub(r'[\s/]', '', city)
        work_years = detail_list[2].xpath('text()')[0].strip()
        work_years = re.sub(r'[\s/]', '', work_years)
        education = detail_list[3].xpath('text()')[0].strip()
        education = re.sub(r'[\s/]', '', education)
        desc = ''.join(html.xpath('//dd[@class="job_bt"]//text()')).strip()
        data = {
            "name": position_name,
            "salay": salary,
            "city": city,
            "work_years": work_years,
            "education": education,
            "desc": desc
        }
        print(data)
        print('+'*40)
        self.positions.append(data)


if __name__ == '__main__':
    spider = Lagouspider()
    spider.run()

希望本文對你有所幫助~~如果對軟件測試、接口測試、自動化測試、面試經驗交流感興趣可以私聊我或關注公衆號“特斯汀軟件測試”。免費領取最新軟件測試大廠面試資料和Python自動化、接口、框架搭建學習資料!技術大牛解惑答疑,同行一起交流。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。