1. 程式人生 > >python3 學習2(分頁翻看百度搜索結果)

python3 學習2(分頁翻看百度搜索結果)

# -*- coding: utf-8 -*-
from selenium import webdriver
import time
if __name__ == "__main__":
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get('http://www.baidu.com')
    
    #通過ID找網頁的標籤,找到搜尋框的標籤    
    seek_input =  driver.find_element_by_id("kw")  
    #設定搜尋的內容    
    seek_input.send_keys("2018財稅新政策") 
    #找到搜尋文件按鈕    
    seek_but = driver.find_element_by_id("su")  
    #並點選搜尋 按鈕    
    seek_but.click() 
    #並點選搜尋 按鈕    
    
    js = 'document.documentElement.scrollTop=10000'#拖動滾動條到底部
    time.sleep(1)
    driver.execute_script(js)
    time.sleep(1)
    total = 0  #頁面數
    is_next_page = True  #存在下一頁
    page_num = 1   #要點選的頁面號
    #往後翻頁
    while is_next_page:
        try:
            total=total+1
            if total == 1 :
                result = driver.find_element_by_xpath("//a[@class='n']")
                text=result.get_attribute('text')
                if text.find('下一頁')>=0 :
                    result.click() 
                    time.sleep(2)
                    driver.execute_script(js)
                    #print('第'+total+'頁')
            else :
                #result = driver.find_element_by_xpath("//a[@class='n']")
                result = driver.find_element_by_link_text("下一頁>") 
                result.click() 
                time.sleep(2)
                driver.execute_script(js)
                print(result)
                #for each_result in result:
                #    text=each_result.get_attribute('text')
                #    if text.find('下一頁')>=0 :
                #        each_result.click() 
                #        time.sleep(2)
                #        driver.execute_script(js)
                        #print('第'+total+'頁')
                        
                
        except:
            print("到最後一頁了")
            break    
      #思路很簡單,不斷獲取下一頁標籤,觸發點選事件,不斷翻頁,  我測的是翻到70頁,文章僅作小白學習筆記,想要獲取每        #頁的  連結地址下載內容可以參考我的上一篇博文