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

selenium调用js方法

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

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

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

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

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

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

代码

python 复制代码
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)


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

优点: 设置一次即可

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

python 复制代码
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


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

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

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

python 复制代码
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版本以后可以变成无头的浏览器,加以下参数

python 复制代码
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()
代理模式
python 复制代码
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()
防检测设置
python 复制代码
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实战案例

python 复制代码
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()
相关推荐
世俗ˊ23 分钟前
CSS入门笔记
前端·css·笔记
子非鱼92124 分钟前
【前端】ES6:Set与Map
前端·javascript·es6
6230_28 分钟前
git使用“保姆级”教程1——简介及配置项设置
前端·git·学习·html·web3·学习方法·改行学it
想退休的搬砖人37 分钟前
vue选项式写法项目案例(购物车)
前端·javascript·vue.js
加勒比海涛1 小时前
HTML 揭秘:HTML 编码快速入门
前端·html
啥子花道1 小时前
Vue3.4 中 v-model 双向数据绑定新玩法详解
前端·javascript·vue.js
麒麟而非淇淋1 小时前
AJAX 入门 day3
前端·javascript·ajax
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
战神刘玉栋1 小时前
《程序猿之设计模式实战 · 观察者模式》
python·观察者模式·设计模式
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践