【问题标题】:how can I get the next page's reviews with selenium?如何使用 selenium 获得下一页的评论?
【发布时间】:2020-01-30 19:52:11
【问题描述】:

我正在尝试从https://www.innisfree.com/kr/ko/ProductReviewList.do 中抓取超过 10 页的评论

但是,当我转到下一页并尝试获取新页面的评论时,我仍然只能获得第一页的评论。

我使用了 driver.execute_script("goPage(2)") 和 time.sleep(5) 但我的代码只给了我第一页的评论。

'''我没有使用for循环只是为了查看page1和page2之间的结果是否不同''' '''我导入了beautifulsoup和selenium'''

这是我的代码:

  url = "https://www.innisfree.com/kr/ko/ProductReviewList.do"

  chromedriver = r'C:\Users\hhm\Downloads\chromedriver_win32\chromedriver.exe'

  driver = webdriver.Chrome(chromedriver)

  driver.get(url)


  print("this is page 1")

  driver.execute_script("goPage(1)")

  nTypes = soup.select('.reviewList ul .newType div[class^=reviewCon] .reviewConTxt')


  for nType in nTypes:

         product = nType.select_one('.pdtName').text

         print(product)


 print('\n')

 print("this is page 2")

 driver.execute_script("goPage(2)")

 time.sleep(5)

 nTypes = soup.select('.reviewList ul .newType div[class^=reviewCon] .reviewConTxt')


 for nType in nTypes:

         product = nType.select_one('.pdtName').text

         print(product)

【问题讨论】:

  • 任何帮助将非常非常感激。谢谢。
  • 你在哪里分配soup?在你打电话给goPage(2) 之后你有没有重新分配汤。哦,请删除多余的空行
  • 如果您使用 selenium,只需单击“下一步”按钮?

标签: python selenium web-scraping beautifulsoup web-crawler


【解决方案1】:

如果您的第二个页面作为新窗口打开,那么您需要切换到另一个页面并将您的 selenium 控件切换到另一个窗口

例子:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

来源:

How to switch to new window in Selenium for Python?

https://www.techbeamers.com/switch-between-windows-selenium-python/

【讨论】:

    【解决方案2】:

    试试下面的代码。您需要点击每个分页链接才能到达下一页。您将获得所有 100 个评论 cmets。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from bs4 import BeautifulSoup
    import time
    url = "https://www.innisfree.com/kr/ko/ProductReviewList.do"
    chromedriver = r'C:\Users\hhm\Downloads\chromedriver_win32\chromedriver.exe'
    driver = webdriver.Chrome(chromedriver)
    driver.get(url)
    
    for i in range(2,12):
       time.sleep(2)
       soup=BeautifulSoup(driver.page_source,'html.parser')
       nTypes = soup.select('.reviewList ul .newType div[class^=reviewCon] .reviewConTxt')
       for nType in nTypes:
          product = nType.select_one('.pdtName').text
          print(product)
       if i==11:
        break
       nextbutton=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//span[@class='num']/a[text()='" +str(i)+"']")))
       driver.execute_script("arguments[0].click();",nextbutton)
    

    【讨论】:

    • 你真的帮了我很多!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2022-06-25
    • 2018-03-21
    • 2016-10-07
    • 2015-11-28
    相关资源
    最近更新 更多