Selenium:如何单击显示按钮,刮除href,然后再次单击显示按钮?

时间:2020-04-15 16:25:08

标签: python selenium-webdriver web-scraping beautifulsoup

链接到我要抓取的页面:

https://www.nytimes.com/reviews/dining

因为此页面上有一个“显示更多”按钮,所以我需要Selenium来自动迭代地单击“显示更多”按钮,然后以某种方式使用美丽汤来收集指向该页面上每个餐厅评论的链接。在下面的照片中,我要收获的链接位于https://...onigiri.html“>。

enter image description here

到目前为止的代码:

url = "https://www.nytimes.com/reviews/dining"
driver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
driver.get(url)

for i in range(1):
  button = driver.find_element_by_tag_name("button")
  button.click()

如何使用WebDriverWait和BeautifulSoup [BeautifulSoup(driver.page_source,'html.parser')]完成此任务?

2 个答案:

答案 0 :(得分:1)

转到https://www.nytimes.com/reviews/dining,按F12键,然后按Ctrl + Shift + C获取元素 Show More ,然后如图所示,获取元素的xpath:

enter image description here

要找到xpath,请查看:

https://www.techbeamers.com/locate-elements-selenium-python/#locate-element-by-xpath

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def executeTest():
    global driver
    driver.get('https://www.nytimes.com/reviews/dining')
    time.sleep(7)
    element = driver.find_element_by_xpath('Your_Xpath')
    element.click()
    time.sleep(3)

def startWebDriver():
    global driver
    options = Options()
    options.add_argument("--disable-infobars")
    driver = webdriver.Chrome(chrome_options=options)

if __name__ == "__main__":
    startWebDriver()
    executeTest()
    driver.quit()

答案 1 :(得分:0)

这是一个延迟加载的应用程序。要单击Show More按钮,您需要使用infinite循环和scroll down来查找页面,然后click并等待一段时间以加载页面,然后将值存储在list中。在列表匹配之前和之后进行验证,然后从无限循环中退出。

代码

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import time

driver=webdriver.Chrome()
driver.get("https://www.nytimes.com/reviews/dining")
#To accept the coockie click on that
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='Accept']"))).click()
listhref=[]

while(True):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    elements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"a.css-gg4vpm")))
    lenlistbefore=len(listhref)
    for ele in elements:
        if ele.get_attribute("href") in listhref:
            continue
        else:
            listhref.append(ele.get_attribute("href"))

    lenlistafter = len(listhref)

    if lenlistbefore==lenlistafter:
        break

    button=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//button[text()='Show More']")))
    driver.execute_script("arguments[0].click();", button)
    time.sleep(2)
print(len(listhref))
print(listhref)

注意:-我正在获取列表数499