使用Selenium和Python进行web抓取时出现的问题

使用Selenium和Python进行web抓取时出现的问题,python,selenium-webdriver,web-scraping,lazy-loading,webdriverwait,Python,Selenium Webdriver,Web Scraping,Lazy Loading,Webdriverwait,我正在努力清理这个网站 有一个按钮可以在单击时加载更多内容,它在不更改URL的情况下显示更多内容 我制作了一段代码,首先加载所有内容,然后提取所有需要的数据URL,然后转到每个链接并刮取数据 url = "https://maroof.sa/BusinessType/BusinessesByTypeList?bid=26&sortProperty=BestRating&DESC=True" driver = webdriver.Chrome() driver.get(url)

我正在努力清理这个网站

有一个按钮可以在单击时加载更多内容,它在不更改URL的情况下显示更多内容 我制作了一段代码,首先加载所有内容,然后提取所有需要的数据URL,然后转到每个链接并刮取数据

url = "https://maroof.sa/BusinessType/BusinessesByTypeList?bid=26&sortProperty=BestRating&DESC=True"
driver = webdriver.Chrome()
driver.get(url)
# button = driver.find_element_by_xpath('//*[@id="loadMore"]/button')
num = 1
while num <= 507:
    sleep(4)
    button = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="loadMore"]/button')))
    button.click()
    print(num)
    num += 1
links = [l.get_attribute('href') for l in WebDriverWait(driver, 40).until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="list"]/a')))]
url=”https://maroof.sa/BusinessType/BusinessesByTypeList?bid=26&sortProperty=BestRating&DESC=True"
driver=webdriver.Chrome()
获取驱动程序(url)
#按钮=驱动程序。通过xpath('/*[@id=“loadMore”]/button')查找元素
num=1
当num单击按钮以加载更多内容时,您需要引导WebDriverWait使
元素成为可点击的()
,您可以使用以下方法:


如果它抛出错误,只需使用try/except。可以初始化一个布尔值,然后循环直到true(通过try-except循环直到它不抛出错误(从而触发except)您是否尝试使用请求?不,我没有尝试使用请求,但我现在将尝试此操作solution@HosamGamal太好了,让我知道你被处决的情况。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions() 
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://maroof.sa/BusinessType/BusinessesByTypeList?bid=26&sortProperty=BestRating&DESC=True')
while True:
    try:
    driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//button[@class='btn btn-primary']"))))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary']"))).click()
    except TimeoutException:
    break
print([l.get_attribute('href') for l in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="list"]/a')))])
driver.quit()