突破淘宝对于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的路径添加进去。

此时会打开一个浏览器页面,我们输入淘宝网址,我们把它当成一个已存在的浏览器:

突破淘宝对于selenium*

 

接下来我们先登录,因为是真实浏览器,所以淘宝是没办法检测的,后面就用脚本去接手这个浏览器,采集即可,随便贴上一段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)