python3使用selenium爬取淘寶寶貝iPhone的信息

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.common.exceptions import TimeoutException

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from pyquery import PyQuery as pq

import re

browser = webdriver.Chrome()

wait = WebDriverWait(browser,10)

def search ():

try:

browser.get('https://www.taobao.com')

input = wait.until(

EC.presence_of_element_located((By.CSS_SELECTOR,'#q'))

)

submit =wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#J_TSearchForm > div.search-button > button')))

input.send_keys('iphone')

submit.click()

total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.total')))

get_products()

return total.text

except TimeoutException:

return search()

def next_page(page_number):

try:

input = wait.until(

EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > input'))

)

submit =wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit')))

input.clear()

input.send_keys(page_number)

submit.click()

wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#mainsrp-pager > div > div > div > ul > li.item.active > span'),str(page_number)))

get_products()

except TimeoutException:

next_page(page_number)

def get_products():

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))

html = browser.page_source

doc = pq(html)

items = doc('#mainsrp-itemlist .items .item').items()

for item in items:

product = {

'image': item.find('.pic .img').attr('src'),

'price': item.find('.price').text(),

'deal': item.find('.deal-cnt').text()[:-3],

? ? ? ? ? ? 'title': item.find('.title').text(),

? ? ? ? ? ? 'shop': item.find('.shop').text(),

? ? ? ? ? ? 'location': item.find('.location').text()

}

print(product)

def main():

total = search()

total = int(re.compile('(\d+)').search(total).group(1))

for i in range(2,total + 1):

next_page(i)

print(total)

file = open('taobaomeishi.txt','a',encoding='utf-8')

# file.write('\n'.join([image,price,deal,title,shop,location]))

file.write('\n' + '=' * 50 + '\n')

file.close()

if __name__ == '__main__':

main()



僅供參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容