使用selenium完成爬虫操作(仅供学习使用)

使用selenium完成爬虫操作

示例:获取京东的信息

Xpath方法

"""
long long away
Date:2022/5/16 15:17
"""
from selenium.webdriver import Chrome,ChromeOptions
from selenium.webdriver.common.keys import Keys
import time,csv
from lxml import etree

# 1.创建配置对象
options = ChromeOptions()
# 设置取消测试环境
options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 设置取消图片加载
options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})

# 2.创建浏览器
b = Chrome(options=options)
b.get('https://www.jd.com/')
# 一、控制输入框输入内容
# 1.获取输入框
search = b.find_element_by_xpath('/html/body/div[1]/div[4]/div/div[2]/div/div[2]/input')
# 2.输入内容
search.send_keys('电脑')
# 3.按回车
search.send_keys(Keys.ENTER)

time.sleep(1)

# 二、页面滚动
# js实现滚动操作:window.scrollBy(x方向的偏移量, y方向偏移量)
# window.scroll
with open('./京东电脑.csv','w',encoding='utf-8',newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['商品名称','商品链接','商品价格','商品评价','店铺名称','店铺链接'])
    s = 0
    for j in range(1,11):
        for i in range (6):
            b.execute_script('window.scrollBy(0, 1000)')
            time.sleep(1)
        root = etree.HTML(b.page_source)

        
        for k in range(1,61):
            try:
                list1 = []
                # 商品名称
                names = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[3]/a/em/text()')
                list1.append(names[k-1])
                # 商品链接
                names_href1 = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[3]/a/@href')
                list1.append('https:'+names_href1[k-1])
                # 价格
                price = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[2]/strong/i/text()')
                list1.append(price[k-1])
                # 评价
                pingjia = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[4]/strong/a/text()')
                list1.append(pingjia[k-1])
                # 店铺名称
                shop_name = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[5]/span/a/text()')
                list1.append(shop_name[k-1])
                # 店铺链接
                shop_href = root.xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[2]/ul/li/div/div[5]/span/a/@href')
                list1.append('https:'+shop_href[k-1])
                writer.writerow(list1)
                s += 1
                print(f'爬取第{s}条')
            except:
                list1.append([])

        # 翻页
        time.sleep(2)
        c = b.find_element_by_xpath('/html/body/div[5]/div[2]/div[2]/div[1]/div/div[3]/div/span[1]/a[9]')
        c.click()
        print('翻页了')


    b.close()

仅供学习使用

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个通过Selenium模拟滑块操作的Python代码示例: ```python from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 配置浏览器驱动 options = webdriver.ChromeOptions() options.add_argument('--disable-extensions') options.add_argument('--disable-infobars') options.add_argument('--profile-directory=Default') options.add_argument('--incognito') options.add_argument('--disable-plugins-discovery') options.add_argument('--start-maximized') # 启动浏览器 browser = webdriver.Chrome(options=options) browser.get('https://www.example.com/login') # 替换成实际的登录页面链接 # 等待页面加载完成 wait = WebDriverWait(browser, 10) username = wait.until(EC.presence_of_element_located((By.NAME, 'username'))) password = wait.until(EC.presence_of_element_located((By.NAME, 'password'))) slider = wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="slider"]'))) submit_btn = wait.until(EC.presence_of_element_located((By.XPATH, '//button[@type="submit"]'))) # 输入账号密码并点击登录 username.send_keys('your_username') password.send_keys('your_password') submit_btn.click() # 等待滑块出现 wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="slide-to-unlock"]'))) # 获取验证码图片和滑块位置信息 captcha_img = browser.find_element_by_xpath('//img[@class="captcha-img"]') slider_btn = browser.find_element_by_xpath('//div[@class="slider-btn"]') captcha_img_location = captcha_img.location slider_location = slider_btn.location # 模拟滑动操作 slider_width = slider_btn.size['width'] ActionChains(browser).click_and_hold(slider_btn).move_by_offset(slider_width, 0).perform() # 检查是否通过了验证码验证 success = wait.until(EC.text_to_be_present_in_element((By.XPATH, '//div[@class="result"]'), '验证成功')) if success: # 验证成功,执行后续操作 print('验证码验证成功') else: # 验证失败,重新进行滑动操作 slider_btn = browser.find_element_by_xpath('//div[@class="slider-btn"]') slider_width = slider_btn.size['width'] ActionChains(browser).click_and_hold(slider_btn).move_by_offset(slider_width, 0).perform() # 关闭浏览器 browser.quit() ``` 需要注意的是,以上代码参考,实际应用中需要根据具体的网页实现进行适当的修改。同时,需要根据网站的反爬虫策略进行相应的调整,例如增加代理IP、使用随机User-Agent等方式来提高爬虫的安全性和稳定性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值