Day:006(3 ) | Python爬虫:高效数据抓取的编程技术(爬虫工具)

 

 selenium调用js方法

        有时候我们需要控制页面滚动条上的滚动条,但滚动条并非页面上的元素,这个时候就需要借助js是来进行操作。

一般用到操作滚动条的会两个场景:

  1. 要操作的页面元素不在当前页面范围,无法进行操作,需要拖动滚动条
  2. 注册时的法律条文需要阅读,判断用户是否阅读的标准是:滚动条是否拉到最下方
调用js的方法 :
execute_script(script, *args)
滚动条回到顶部: 
js="document.getElementById('id').scrollTop=0"
driver.execute_script(js)
滚动条拉到底部:
js="document.documentElement.scrollTop=10000"
driver.execute_script(js)

        可以修改scrollTop 的值,来定位右侧滚动条的位置,0是最上面,10000是最底部

        以上方法在Firefox和IE浏览器上上是可以的,但是用Chrome浏览器,发现不管用。Chrome浏览器解决办法: 

js = "document.body.scrollTop=0"
driver.execute_script(js)
横向滚动条:
js = "window.scrollTo(100,400)"
driver.execute_script(js)

代码

from selenium.webdriver.chrome.service
import Service
from selenium import webdriver
from time import sleep
from lxml import etree

def test_scroll():
    # 创建驱动
    s = Service('./chromedriver.exe')
    # 创建浏览器
    driver = webdriver.Chrome(service=s)
    # 访问页面
driver.get("https://search.jd.com/Search?
keyword=%E6%89%8B%E6%9C%BA&enc=utf8&suggest=1.def.0.SAK7|MIXTAG_SAK7R,SAK7_M_A
M_L5385,SAK7_M_COL_R,SAK7_S_AM_R,SAK7_SC_PD_
R,SAK7_SM_PB_R,SAK7_SS_PM_R,tsabtest_base64_
U2VhcmNobGlzdF80MzkyfGJhc2U_tsabtest|&wq=sho
uji&pvid=24340a2def0e4e0cb510af07aa32c89d")

# 拉动滚动条到底部
    js='document.documentElement.scrollTop=100000'
    driver.execute_script(js)
    sleep(1)
    # 创建一个etree对象,用于解析数据
    e = etree.HTML(driver.page_source)
    # 获取数据价格
    prices = e.xpath('//ul[@class="gl-warpclearfix"]/li/div/div/strong/i/text()')
    print(prices)
    print(len(prices))
    # 关闭浏览器
    sleep(3)
    driver.quit()

if __name__ =='__main__':
    test_scroll()

selenium 等待元素

  • 网速慢
  • AJAX请求数据
  • 调试
强制等待 

使用 time.sleep

作用:当代码运行到强制等待这一行的时候,无论出于什么原因,都强制等待指定的时间,需要通过time模块实现

优点:简单

缺点:无法做有效的判断,会浪费时间 

隐式等待

chrome.implicitly_wait(time_num)



到了一定的时间发现元素还没有加载,则继续等待我们指定的时间,如果超过了我们指定的时间还没有加载就会抛出异常,如果没有需要等待的时候就已经加载完毕就会立即执行

优点: 设置一次即可

缺点:必须等待加载完成才能到后续的操作,或者等待超时才能进入后续的操作 

from selenium import webdriver
url = 'https://www.baidu.com/'
driver = webdriver.Chrome()
driver.get(url)
driver.implicitly_wait(10)
print(driver.find_element_by_class_name('next'))
print(driver.page_source)
显示等待

from selenium.webdriver.support.wait import WebDriverWait



指定一个等待条件,并且指定一个最长等待时间,会在这个时间内进行判断是否满足等待条件,如果成立就会立即返回,如果不成立,就会一直等待,直到等待你指定的最长等待时间,如果还是不满足,就会抛出异常,如果满足了就会正常返回

优点:专门用于对指定一个元素等待,加载完即可运行后续代码

缺点:多个元素都需要要单独设置等待 

url = 'https://www.guazi.com/nj/buy/'
driver = webdriver.Chrome()
driver.get(url)
wait = WebDriverWait(driver,10,0.5)
wait.until(EC.presence_of_element_located((By
.CLASS_NAME, 'next')))
print(driver.page_source)

selenium 参数使用

chrome59版本以后可以变成无头的浏览器,加以下参数

def test_headless():
    # 设置参数,将浏览器隐藏起来(无头浏览器)
    options = ChromeOptions()
    options.add_argument('--headless')
    # 设置驱动
service = Service('./chromedriver')
    # 启动Chrome浏览器
    driver =Chrome(service=service,options=options)
    # 访问页面
    driver.get('https://www.baidu.com')
    # 打印代码
    print(driver.page_source)
    # 关闭浏览器
    driver.quit()
 代理模式
def test_proxy1():
    # 设置参数,给浏览器设置代理
    options = ChromeOptions()
    # options.add_argument('--proxyserver=http://ip:port')
    options.add_argument('--proxyserver=http://221.199.36.122:35414')
    # 设置驱动
    service = Service('./chromedriver')
    # 启动Chrome浏览器
    driver =Chrome(service=service,options=options)
    # 访问页面 "134.195.101.16",
    driver.get('http://httpbin.org/get')
    # 打印代码
    print(driver.page_source)
    # 关闭浏览器
    driver.quit()

def test_proxy2():
    from selenium.webdriver.common.proxy
import ProxyType,Proxy
    # 设置参数,给浏览器设置代理
    ip = 'http://113.76.133.238:35680'
    proxy = Proxy()
    proxy.proxy_type = ProxyType.MANUAL
    proxy.http_proxy = ip
    proxy.ssl_proxy = ip
    # 关联浏览器
    capabilities =DesiredCapabilities.CHROME
    proxy.add_to_capabilities(capabilities)
    # 设置驱动
    service = Service('./chromedriver')
    # 启动Chrome浏览器
    driver =Chrome(service=service,desired_capabilities=capabilities)
    # 访问页面 "134.195.101.16",
    driver.get('http://httpbin.org/get')
    # 打印代码
    print(driver.page_source)
    # 关闭浏览器
    driver.quit()
 防检测设置

 

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions

options = ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomati
onExtension', False)

chrome = Chrome(chrome_options=options)

chrome.execute_cdp_cmd("Page.addScriptToEval
uateOnNewDocument", {
    "source": """
       Object.defineProperty(navigator,
'webdriver', {
       get: () => false
       })
   """
})

chrome.get('http://httpbin.org/get')
info = chrome.page_source

print(info)
sleep(20)

使用 window.navigator.webdriver 检测 

Selenium实战案例 

from selenium.webdriver.chrome.service
import Service
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By

from lxml import etree

def spider_huya():
    # 创建一个驱动
    service = Service('./chromedriver.exe')
    # 创建一个浏览器
    driver = Chrome(service=service)
    # 设置隐式等待
    driver.implicitly_wait(5)
    # 访问网址
    driver.get('https://www.huya.com/g/lol')
    count = 1
    while True:
        # print('获取了第%d页' % count)
        # count += 1
        # 提取数据
        e = etree.HTML(driver.page_source)
        names =e.xpath('//i[@class="nick"]/@title')
        person_nums =e.xpath('//i[@class="js-num"]/text()')
        # 打印数据
        # for n,p in zip(names,person_nums):
        #     print(f'主播名:{n} 人气:{p}')
        # 找到下一页的按钮
        # try:
        #     next_btn =driver.find_element(By.XPATH,'//a[@class="laypage_next"]')
        #     next_btn.click()
        # except Exception as e:
        #     break
        if
driver.page_source.find('laypage_next') ==-1:
            break
        next_btn =driver.find_element(By.XPATH,'//a[@class="laypage_next"]')
        next_btn.click()
        
    # 关闭浏览器
    driver.quit()

if __name__ == '__main__':
    spider_huya()

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值