Очистка веб-страниц BeautifulSoup find_all не работает в APEC

#python #html #web-scraping #beautifulsoup

#python #HTML #очистка веб-страниц #beautifulsoup

Вопрос:

исходный код страницы такой, как на картинке

Я хочу найти весь контейнер класса div-результат, но это не работает, я получаю пустой список

мой код: `

 from bs4 import BeautifulSoup, NavigableString, Tag
import requests
import urllib.request
url = "https://www.apec.fr/candidat/recherche-emploi.html/emploi?page="
for page in range(0,10,1):
    r = requests.get(url   str(page))
    soup = BeautifulSoup(r.content,"html.parser")
    ancher = soup.find_all('div', attrs={'class': 'container-result'})
print(ancher)
 

`

Ответ №1:

Поскольку веб-страница отображается с помощью javascript, requests / BeautifulSoup не сможет извлекать необходимые элементы DOM, поскольку они добавляются через некоторое время во время отображения страницы. Вы могли бы попробовать использовать selenium для этой цели, вот пример:

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

# delay for selenium web driver wait
DELAY = 30

# create selenium driver
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument('--headless')
#chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('<<PATH TO chromedriver>>', options=chrome_options)

# iterate over pages
for page in range(0, 10, 1):
    
    # open web page
    driver.get(f'https://www.apec.fr/candidat/recherche-emploi.html/emploi?page={page}')
    
    # wait for element with class 'container-result' to be added
    container_result = WebDriverWait(driver, DELAY).until(EC.presence_of_element_located((By.CLASS_NAME, "container-result")))
    # scroll to container-result
    driver.execute_script("arguments[0].scrollIntoView();", container_result)
    # get source HTML of the container-result element
    source = container_result.get_attribute('innerHTML')
    # print source
    print(source)
    # here you can continue work with the source variable either using selenium API or using BeautifulSoup API:
    # soup = BeautifulSoup(source, "html.parser")

# quit webdriver    
driver.quit()