UI登陸淘寶搜尋某物品並寫入excel

Dqking0714發表於2020-10-08

自己寫的登入淘寶搜尋物品 將所搜到的資訊寫入excel中
其他的細節自己弄

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
from openpyxl import Workbook


driver = webdriver.Chrome()
driver.get('https://www.taobao.com/')
driver.maximize_window()
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.LINK_TEXT,'親,請登入'))).click()#進入登陸介面
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.NAME,'fm-login-id'))).send_keys('dqking0714')#使用者名稱
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.NAME,'fm-login-password'))).send_keys('dqking0714')#密碼
'''使用者名稱和密碼自己改'''
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CLASS_NAME,'fm-btn'))).click()#點選登陸
WebDriverWait(driver,25).until(EC.visibility_of_element_located((By.CLASS_NAME,'search-combobox-input'))).send_keys('電腦')#搜尋某商品
'''搜尋其他的,比如電腦,鍵盤等自己改'''
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CLASS_NAME,'search-button'))).click()#開始搜尋
page_all = WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CLASS_NAME,'total'))).text#獲取一共有多少頁,返回為字串,舉例:   共 100 頁,
page = int(page_all.split()[1])#將字串全部擷取成為列表後選擇頁碼並轉換成數字型
a = 1
b = 2
wa = Workbook()
shuju = wa.active
shuju['A1'] = '商鋪'
shuju['B1'] = '商鋪描述'
shuju['C1'] = '價格'
shuju['D1'] = '購買人數'
shuju['E1'] = '商鋪地址'
for a in range(1,page+1):
    print('這是第', a, '頁資料')
    items = WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,'//div[@class="items"]/div[@class="item J_MouserOnverReq  "]')))#xpath相對路徑
    '''引數,價格,店鋪,付款人數,廠家地方'''
    for item in items:
        price =WebDriverWait(item,3).until(EC.visibility_of_element_located((By.XPATH,'.//strong'))).text#價格
        buy_person = WebDriverWait(item,3).until(EC.visibility_of_element_located((By.XPATH,'.//div[@class="deal-cnt"]'))).text#購買人數
        desc = WebDriverWait(item,3).until(EC.visibility_of_element_located((By.XPATH,'.//div[@class="row row-2 title"]/a'))).text#描述
        store = WebDriverWait(item,3).until(EC.visibility_of_element_located((By.XPATH,'.//div[@class="shop"]/a'))).text#商鋪名
        place = WebDriverWait(item,3).until(EC.visibility_of_element_located((By.XPATH,'.//div[@class="location"]'))).text#商鋪地址
        shuju['A'+str(b)] = store
        shuju['B'+str(b)] = desc
        shuju['C'+str(b)] = price
        shuju['D'+str(b)] = buy_person
        shuju['E'+str(b)] = place
        b = b+1
        print(price,buy_person,desc,store,place)
    WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//a[@class="J_Ajax num icon-tag"]'))).click()
    a = a + 1
wa.save('E:\pycharm\PyCharm Community Edition 2020.2.2\py_project\TaoBao\shuju.xlsx')#將資料寫入excel
time.sleep(5)
driver.quit()#關閉瀏覽器

相關文章