python day05

selenium基本使用

一、实例一

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

import  time

driver = webdriver.Chrome()

try:
    #隐式等待
    driver.implicitly_wait(10)

    driver.get('https://www.jd.com/')

    #time.sleep(10)
    input_tag = driver.find_element_by_id('key')

    input_tag.send_keys('彩色铅笔')

    input_tag.send_keys(Keys.ENTER)

except Exception as e:
    print(e)

# finally:
#     driver.close()

二、实例二

from selenium import webdriver
# 导入键盘Keys
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()

# 检测代码块
try:
    # 隐式等待,等待标签加载
    driver.implicitly_wait(10)

    # 往京东主页发送请求
    driver.get('https://www.jd.com/')

    # 通过id查找input输入框
    input_tag = driver.find_element_by_id('key')

    # send_keys为当前标签传值
    input_tag.send_keys('中华字典')

    # 按键盘的回车键
    input_tag.send_keys(Keys.ENTER)

    time.sleep(3)

    '''
    爬取京东商品信息:
        
            名称
            url
            价格
            评价
    '''
    # element 找一个
    # elements 找多个
    # 查找所有的商品列表
    good_list = driver.find_elements_by_class_name('gl-item')
    # print(good_list)

    # 循环遍历每一个商品
    for good in good_list:
        # 通过属性选择器查找商品详情页url
        # url
        good_url = good.find_element_by_css_selector('.p-img a').get_attribute('href')
        print(good_url)

        # 名称
        good_name = good.find_element_by_css_selector('.p-name em').text
        print(good_name)

        # 价格
        good_price = good.find_element_by_class_name('p-price').text
        print(good_price)

        # 评价数
        good_commit = good.find_element_by_class_name('p-commit').text
        print(good_commit)


        str1 = f'''
        url: {good_url}
        名称: {good_name}
        价格: {good_price}
        评价: {good_commit}
        \n
        '''
        # 把商品信息写入文本中
        with open('jd.txt', 'a', encoding='utf-8') as f:
            f.write(str1)


    time.sleep(10)

# 捕获异常
except Exception as e:
    print(e)

# 最后都会把驱动浏览器关闭掉
finally:
    driver.close()

 

上一篇:python day05


下一篇:UC学习day05 内存管理 文件基本操作