簡體   English   中英

無法使用python硒刮下一頁(分頁)

[英]Unable to scrape the next page(pagination) using python selenium

我試圖從konga.com抓取數據。 但是我能夠刮開第一頁,但是第二頁卻出現了問題。 我還復制了該網站的第2頁的網址,但它確實起作用。 代碼如下:

from selenium import webdriver
import time

browser = webdriver.Chrome(executable_path='C:\Python27\Scripts\chromedriver.exe')

for i in range(1,50):
   y= '%0d'%i
   url="https://www.konga.com/category/electronics-5261?"+ "page="+'%0d'%i
   print url
   browser.get("url")


p=browser.find_elements_by_xpath ("//div[@class='af885_1iPzH']/h3")

for a in p:
        print '.........page'+ str(i)+ '..........' 
        print a.text

你近了 問題是您試圖在將類名實際加載到頁面之前找到它。 分頁鏈接也一樣。 看起來這些元素在加載頁面之前幾秒鍾沒有完全加載。 您需要做的是讓Webdriver等待幾秒鍾,直到使用WebDriverWait方法看到該元素為止:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--hide-scrollbars')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument("--log-level=3")  # fatal


page = 0

browser = webdriver.Chrome(executable_path=r'C:\Users\edekio\Downloads\chromedriver.exe', chrome_options=chrome_options)

url = "https://www.konga.com/category/electronics-5261"
browser.get(url)

while page < 51:

    page = page + 1


    next_page = WebDriverWait(browser, 15).until(EC.presence_of_element_located((By.LINK_TEXT, str(page))))
    next_page.click()


    print("page " + str(page))

    element = WebDriverWait(browser, 15).until(
        EC.presence_of_element_located((By.CLASS_NAME, "af885_1iPzH")))
    print(element.text)

前三頁的輸出:

page 1
Q18 Smartwatch - Silver
page 2
Zealot S12 Bluetooth Wireless Speaker...
page 3
I8 Tws Wireless Earbuds - White

這是用python 3.6編寫的。 看來您使用的是python 2.x,但是如果它不適用於您的版本,則可以使用在線轉換器。 我建議升級到Selenium的python 3.6,因為我不知道它們的所有功能是否都適用於Python2.x。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM