day24selenuim的高级用法

day24selenuim的高级用法

1网页滚动爬取京东数据

from selenium.webdriver import Chrome,ChromeOptions
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time,csv
#1创建配置对象
options=ChromeOptions()

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

#3创建浏览器对象
b=Chrome(chrome_options=options)
b.get('https://www.jd.com')
#找到输入框输入运动鞋
search=b.find_element_by_css_selector('#key')
search.send_keys('运动鞋')
search.send_keys(Keys.ENTER)


#执行js的滚动代码
#滚动一次
# b.execute_script('window.scrollTo(X左右坐标像素,Y上下坐标像素)')
#一次次的动
height=500
for i in range(10):
    b.execute_script(f'window.scrollTo(0,{height})')
    height+=800
    time.sleep(1)

soup=BeautifulSoup(b.page_source,'lxml')
all_good=soup.select('.gl-warp>li')
print(len(all_good))
list1=[]
for good in all_good:
    #品类名
    name=good.select_one('.p-name.p-name-type-2 em').text
    # print(name)
    #评价
    evaluate=good.select_one('.p-commit a').text
    # print(evaluate)
    # #店名
    shop=good.select_one('.J_im_icon>a').text
    # print(shop)
    # # 价格
    price = good.select_one('.p-price i').text
    # print(price)
    list1.append([name,evaluate,shop,price])
f=open('file/jd鞋子情况.csv','w',encoding='utf-8',newline='')
writer=csv.writer(f)
writer.writerow(['名字','评价','店名','价格'])
writer.writerows(list1)

2显式等待和隐式等待

#1创建等待对象
wait=WebDriverWait(b,10)

#2给出等待条件
"""
等待对象.until(条件)
等待对象.until_not(条件)
"""
# wait.until(EC.presence_of_element_located(标签)-- 等到一个元素出现为止,这个标签是个元组(By.css_seleter,'key')
# wait.until(EC.text_to_be_present_in_element_value(标签,内容))-等到指定的标签的元素出现为止,也是元组((By.ID,'key'),'鞋子')
#value一般检测输入框内容
# wait.until(EC.text_to_be_present_in_element_value(标签,内容))-等到包含的双标签的元素出现为止,也是元组((By.ID,'key'),'鞋子')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值