1. 程式人生 > >筆記-selenium+chrome headless

筆記-selenium+chrome headless

筆記-selenium+chrome headless

 

1.      selenium+chrome headless

phantomjs與selenium分手了,建議使用其它無頭瀏覽器。

chrome也提供了無頭瀏覽器,找到對應版本搭建測試環境。

 

1.1.    常規使用

先上程式碼,下面是常用呼叫方式。

from selenium.webdriver.chrome.options import Options

 

url = 'https://www.guazi.com/bj/buy/'

urls = ['https://www.taobao.com/','https://www.tmall.com/','https://www.csdn.net/']

 

time1 = time.time()

try:

    cookie_t = {}

    chrome_option = Options()

    chrome_option.add_argument('--headless')

    #chrome_option.add_argument('--disable-gpu')

    browser = webdriver.Chrome(chrome_options=chrome_option)

    browser.get(url)

    cookie_t['antipas'] = browser.get_cookie('antipas')['value']

    print(cookie_t)

    for _ in urls:

        browser.get(_)

        time.sleep(3)

        with open('xxx.txt','a+',encoding='utf-8') as fi:

            fi.write(browser.page_source)

   

browser.close()

except:

    print('error')

finally:

browser.quit()

    time2 = time.time()

    print(time2-time1)

 

     爬蟲的程式碼有一點需要注意,需要操作事件的時候最好不要直接用相應的方法,比如click。最好嵌入js指令碼的方式進行呼叫。因為爬蟲的程式碼執行速度很快,前端元素結構往往反應不過來,從而找出元素不可見或者不存在的錯誤。

 

 

其它常用設定項:

# 設定代理

chromeOptions.add_argument("--proxy-server=http://202.20.16.82:10152")

# 一定要注意,=兩邊不能有空格,不能是這樣--proxy-server = http://202.20.16.82:10152

browser = webdriver.Chrome(chrome_options = chromeOptions)

 

1.2.    更多設定及操作項

1.2.1.   對於瀏覽器視窗的操作

在瀏覽器中有些操作是使用系統原生的確認框,這時就無法通過定位元素的方式來操作我們需要的步驟。這種情況就要去操作瀏覽器的視窗來實現。

1.彈出視窗為Confirm型別

選擇確認:

Alert al = driver.switchTo().alert();

al.accept();

選擇取消:

Alert al = driver.switchTo().alert();

al.dismiss();

2.彈出視窗為Alert型別

Alert al = driver.switchTo().alert();

al.accept();

3.放大瀏覽器視窗

driver.manage().window().maximize();

 

4.關閉瀏覽器視窗

driver.quit();

driver.close();

 

5.重新整理/前進/後退瀏覽器

driver.navigate().refresh();

driver.navigate().forward();

driver.navigate().back();

quit和close的區別在於,quit關閉整個瀏覽器的視窗;close關閉瀏覽器標籤頁。

 

1.2.2.   程式等待方式

在使用selenium的過程中,等待web載入時,通常要等待下一個元素出現再進行操作,這個過程中需要用到等待。selenium中有3種等待:webDriverWait()、implicitly_wait()、sleep().

 

1)sleep():強制等待,設定固定的休眠時間。任何情況下都等待設定的時間。

//引入前匯入相應的包,單位為毫秒;

sleep(5);

2)implicitly_wait():隱式等待,等待一個元素被發現、命令完成,超出了設定的時間則跑出異常;

 //設定指令碼在查詢元素時的最大等待時間

 WebDriver driver = new ChromeDriver();

 driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

3)webDriverWait():顯示等待,明確要等待的元素在指定時間之內沒找到,那麼就丟擲Exception.

 

//設定等待的時長,最長10S

WebDriverWait wait = new WebDriverWait(driver, 10);  wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@id='appContentContainer']/div/div/div[1]/div[2]/div/div/button")));