warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '報錯


問題:selenium已經放棄PhantomJS,建議使用火狐或者谷歌無界面瀏覽器。

解決方案1:

selenium版本降級

通過pip install selenium默認安裝版本。 (通過pip show selenium顯示版本)
將其卸載pip uninstall selenium,重新安裝並指定版本號pip install selenium==2.48.0。

解決方案2:

使用別的瀏覽器,我這里使用的Chrome;

安裝教程網上很多https://segmentfault.com/a/1190000013940356

實例:(采集北京市政百姓信件內容)

 

from lxml import etree
import requests
import csv
from selenium import webdriver
import time
import os
from selenium.webdriver.chrome.webdriver import WebDriver

#創建csv
outPath = 'D://xinfang_data.csv'
if (os.path.exists(outPath)):
    os.remove(outPath)
fp = open(outPath, 'wt', newline='', encoding='utf-8')  # 創建csv
writer = csv.writer(fp)
writer.writerow(('kind', 'time', 'processingDepartment', 'content'))

#請求頭
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}

# 創建瀏覽器對象
driver = webdriver.Chrome()

# 得到網頁信息
def get_info(num):
    driver.get(url)
    driver.implicitly_wait(10)  # 隱式等待n秒,解釋JavaScript是需要時間的,如果短了就無法正常獲取數據,如果長了浪費時間;implicitly_wait()給定時間智能等待
    #driver.find_element_by_xpath('//*[@id="pageNum"]').clear()
    driver.find_element_by_id('pageNum').clear()#清除輸入框
    #driver.find_element_by_id('pageNum').send_keys(num)
    driver.find_element_by_xpath('//*[@id="pageNum"]').send_keys(num)#輸入頁數
    driver.find_element_by_xpath('//*[@id="judgeFlag"]/a').click()#單擊確認框
    time.sleep(1)#一定要停一下,否則加載不出來一直輸出第一頁
    #print(driver.current_window_handle)#當前頁面句柄
    html = driver.page_source
    #print(driver.page_source)
    return html

#解析HTML文件,獲取數據
def get_data(html):
    selector = etree.HTML(html)
    infos=selector.xpath('//*[@id="mailul"]/div')
    for info in infos:
        kind=info.xpath('div[1]/a/font/text()')[0]
        time=info.xpath('div[2]/div[1]/div[1]/text()')[0]
        processingDepartment = info.xpath('div[2]/div[1]/div[2]/span/text()')[0]
        content = info.xpath('div[1]/a/span/text()')[0]
        #處理得到的字符串
        parsekind=kind.strip().strip('·【').strip('')
        #print(parsekind)
        parsetime=time.strip().strip('發起時間:').replace("-", "/")
        #print(parsetime)
        parsepd = processingDepartment.strip().strip('處理部門:')
        #print(parsepd)
        parsecontent = content.strip()
        #print(parsecontent)
        #寫入csv
        writer.writerow((parsekind,parsetime,parsepd,parsecontent))

if __name__ == '__main__':
    url = 'http://www.beijing.gov.cn/hudong/hdjl/com.web.search.mailList.flow'
    for i in range(1,1000):
        html=get_info(i)
        get_data(html)
        time.sleep(1)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM