链接到我要抓取的页面:
https://www.nytimes.com/reviews/dining
因为此页面上有一个“显示更多”按钮,所以我需要Selenium来自动迭代地单击“显示更多”按钮,然后以某种方式使用美丽汤来收集指向该页面上每个餐厅评论的链接。在下面的照片中,我要收获的链接位于https://...onigiri.html“>。
到目前为止的代码:
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')]完成此任务?
答案 0 :(得分:1)
转到https://www.nytimes.com/reviews/dining,按F12键,然后按Ctrl + Shift + C获取元素 Show More ,然后如图所示,获取元素的xpath:
要找到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