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()
相关推荐
橙子家3 小时前
浏览器缓存之【基础键值存储】:Local storage 和 Session storage
前端
程序员龙叔5 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
星星在线5 小时前
MusicFree:一个「All in One」的个人音乐服务器,让听歌回归简单
前端·后端
IT_陈寒6 小时前
Redis的SETNX并发问题让我加了三天班
前端·人工智能·后端
demo007x7 小时前
Docling 文档转换以及技术架构分析
前端·后端·程序员
京东云开发者7 小时前
京东市民服务又“上新”!这次是黑龙江“龙易办”
前端
袋鱼不重8 小时前
我的神奇同事,AI 用多了居然写了个 Open In Codex
前端·后端·ai编程
用户8356290780518 小时前
使用 Python 操作 Word 内容控件
后端·python
竹林8188 小时前
Web3表单签名验证:我用 wagmi 和 ethers 给 DApp 加了一个“免密登录”,踩坑记录全在这了
javascript
用户6990304848758 小时前
try catch使用场景 处理同步代码错误兼容用的
javascript·uni-app