day05 应用selenium的一个小实例

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')
    # 循环遍历每一个商品
    for good in good_list:
        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()

 

posted @ 2019-06-28 19:41  Cpoison  阅读(136)  评论(0编辑  收藏  举报