突破淘寶對於selenium檢測

去年11月之前淘寶對於selenium還是很友好的,後來selenium被檢測了window.navigator.webdriver 等參數,出滑動驗證碼什麼的,selenium已經很難用了,  網上大片教程都使用的pyppeteer 修改檢測js參數去採集, 我也用了一段時間, 但是發現chromium佔用內存太高,並且pyppeteer參數方法介紹太少,用起來不舒服,本文介紹了另一種方法:使用selenium接管現有瀏覽器

利用Chrome DevTools協議。它允許客戶檢查和調試Chrome瀏覽器。

打開cmd,在命令行中輸入命令:

chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"

對於-remote-debugging-port值,可以指定任何打開的端口。

      對於-user-data-dir標記,指定創建新Chrome配置文件的目錄。它是爲了確保在單獨的配置文件中啓動chrome,不會污染你的默認配置文件。

      還有,不要忘了在環境變量中PATH裏將chrome的路徑添加進去。

此時會打開一個瀏覽器頁面,我們輸入淘寶網址,我們把它當成一個已存在的瀏覽器:

 

接下來我們先登錄,因爲是真實瀏覽器,所以淘寶是沒辦法檢測的,後面就用腳本去接手這個瀏覽器,採集即可,隨便貼上一段demo.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

driver = webdriver.Chrome(chrome_options=chrome_options)
print(driver.title)

#當前句柄
current = driver.current_window_handle

driver.execute_script('window.open("http://www.baidu.com")')


#所有句柄
heandles = driver.window_handles
secondhand = heandles[-1]

#切回first
driver.switch_to.window(current)

page_num = 0
while page_num < 15:
    print(page_num+1)

    url = 'https://s.taobao.com/search?spm=a21bo.2017.201856-fline.3.5af911d9CJTHFx&q=T%E6%81%A4&refpid=420462_1006&source=tbsy&style=grid&tab=all&pvid=d0f2ec2810bcec0d5a16d5283ce59f67&bcoffset=0&p4ppushleft=3%2C44&s={0}'.format(44*page_num)
    driver.get(url)
    time.sleep(3)
    page_list = driver.find_elements_by_xpath('//div[@id = "mainsrp-itemlist"]/div[@class="m-itemlist"]/div/div[@class="items"]/div')
    print(page_list)
    if page_list:
        for pageli in page_list:

            #切第二個標籤頁

            item_url = pageli.find_element_by_xpath('./div[1]/div[1]/div[1]/a[@class="pic-link J_ClickStat J_ItemPicA"]').get_attribute('href')

            if not re.findall('http', item_url):
                item_url = 'https:' + item_url
            print(item_url)
            driver.switch_to.window(secondhand)
            driver.get(item_url)
            time.sleep(5)
            print(driver.title)
            driver.switch_to.window(current)
        else:
            #切回第一頁
            driver.switch_to.window(current)
    page_num +=1
    time.sleep(2.5)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章