我正在嘗試使用 Selenium 和 Python 對 Aliexpress 進行網路抓取,一切似乎都很好。我遇到的問題是我的代碼只從每個頁面中抓取 10 個產品而不是所有產品,我仍然不知道其背后的原因。這是我的代碼:
from selenium import webdriver
from lxml import html
from time import sleep
from itertools import zip_longest
import csv
driver = webdriver.Edge(executable_path=r"C:/Users/OUISSAL/Desktop/wscraping/XEW/scraping/codes/msedgedriver")
with open ("data.csv", "w", encoding="utf-8") as csvfile:
wr = csv.writer(csvfile)
wr.writerow(["Title","Price", "Currency", "Reviews", "Number of orders"])
for page_nb in range (1,4):
driver.get('https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText=bluetooth earphones<ype=wholesale&SortType=default&page={}'.format(page_nb))
sleep(1)
tree = html.fromstring(driver.page_source)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
sleep(10)
for product_tree in tree.xpath('/html/body/div[3]/div/div/div[2]/div[2]/div/div[2]'):
title = product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[1]/h1/text()')
price = product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[2]/span[2]/text()')
currency = product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[2]/span[1]/text()')
review = product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[4]/span[2]/text()')
nb_sold = product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[4]/span[1]/text()')
list = [title, price, currency, review, nb_sold]
exported = zip_longest(*list)
wr.writerows(exported)
print(list)
driver.close()
此外,我正在嘗試獲取每個產品的網址以提取評論和評論。我正在使用這段代碼:
........
productlink = 'https://www.aliexpress.com' str(product_tree.xpath('//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]/a/@href'))
list = [title, price, currency, review, nb_sold, productlink]
.......
這就是我得到的結果,它一次將https://www.aliexpress.com與所有 url 連接起來,而不是每一個。 在此處輸入圖片描述 謝謝!
uj5u.com熱心網友回復:
有兩個問題:
第一的:
您必須在向下滾動后html.fromstring(driver.page_source) 使用。
第二:
它僅在專案顯示在視窗(in viewport)內時添加專案,因此您不能直接跳轉到頁面末尾。您必須使用 ie 部分滾動(回圈)window.innerHeight。
current_offset = 0
while True:
driver.execute_script("window.scrollBy(0, window.innerHeight);")
sleep(.5) # JavaScript has time to add elements
new_offset = driver.execute_script("return window.pageYOffset;")
#print(new_offset,current_offset)
if new_offset <= current_offset:
break
current_offset = new_offset
具有其他更改的完整作業代碼xpath。
它在每頁上給了我 60 個專案。
from selenium import webdriver
from lxml import html
from time import sleep
from itertools import zip_longest
import csv
driver = webdriver.Edge(executable_path=r"C:/Users/OUISSAL/Desktop/wscraping/XEW/scraping/codes/msedgedriver")
#driver = webdriver.Firefox()
url = 'https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText=bluetooth earphones<ype=wholesale&SortType=default&page={}'
with open ("data.csv", "w", encoding="utf-8") as csvfile:
wr = csv.writer(csvfile)
wr.writerow(["Title","Price", "Currency", "Reviews", "Number of orders"])
for page_nb in range(1, 4):
print('---', page_nb, '---')
driver.get(url.format(page_nb))
sleep(2)
# jump to the end of page
#driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
# scroll partially
current_offset = 0
while True:
driver.execute_script("window.scrollBy(0, window.innerHeight);")
sleep(.5) # JavaScript has time to add elements
new_offset = driver.execute_script("return window.pageYOffset;")
print(new_offset,current_offset)
if new_offset <= current_offset:
break
current_offset = new_offset
sleep(3)
tree = html.fromstring(driver.page_source)
results = []
for product in tree.xpath('//div[@]//a'):
title = product.xpath('.//h1/text()')
#print('[DEBUG] title:', title)
if title:
title = title[0]
#print('[DEBUG] title:', title)
price = product.cssselect('div.mGXnE._37W_B span')
price = [x.text for x in price]
# for `$ 35.00`
currency = price[0]
price = ''.join(price[1:])
# for `35.00 z?`
#currency = price[-1]
#price = ''.join(price[:-1])
#print('[DEBUG] price:', price)
#print('[DEBUG] currency:', currency)
review = product.xpath('.//span[@]/text()')
if review:
review = review[0]
else:
review = ''
#print('[DEBUG] review:', review)
nb_sold = product.xpath('.//span[@]/text()')
if nb_sold:
nb_sold = nb_sold[0]
else:
nb_sold = ''
#print('[DEBUG] nb_sold:', nb_sold)
row = [title, price, currency, review, nb_sold]
results.append(row)
#print('[DEBUG] row:', row)
print('len(results):', len(results))
wr.writerows(results)
driver.close()
uj5u.com熱心網友回復:
您需要盡量減少使用Xpath。
嘗試通過 CSS 語法查找元素,例如:
這將找到一個在其類屬性中包含單詞 123 的 div 元素
"div[class*='123']"
這將通過 Xpath 找到一個必須在其文本中包含 Hello 的元素:
"*[text(contains(),'Hello')]"
您應該避免使用長 Xpath 根目錄,因為它不可讀并且需要更長的時間來執行。在您練習了一些 CSS 和 Xpath 選擇器之后,您會更容易找到元素、單擊它們或讀取其中的資料。
此外,僅 1 秒的睡眠在將來可能無效。該站點可能會以一些延遲回應,您將在 3 秒或更長時間后看到您發現的內容。閱讀了解WebDriverWait如何等待特定閾值和等待條件的元素
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/442004.html
