import requests
from bs4 import BeautifulSoup
import json
from lxml import html
# def scrape_company_urls(url):
# response = requests.get(url)
# if response.status_code != 200:
# print(f"Failed to retrieve page. Status code: {response.status_code}")
# return None
# soup = BeautifulSoup(response.content, 'html.parser')
# container = soup.find('div', class_='search_cardsContainer__jTGn4')
# if container:
# links = container.find_all('a', href=True)
# # Extract company names, filter out '/de', and remove duplicates
# company_names = list(set(
# link['href'].split('/')[-1] for link in links if link['href'] != '/de'
# ))
# return json.dumps(company_names)
# return None
# def scrape_company_strengths(url_company):
# response = requests.get(url_company)
# if response.status_code != 200:
# print(f"Failed to retrieve page. Status code: {response.status_code}")
# return None
# soup = BeautifulSoup(response.content, 'html.parser')
# strength_section = soup.find('section', class_='index__topFactorList__J8yDG')
# if strength_section:
# strengths = {}
# for item in strength_section.find_all('li', class_='index__container__yePeh'):
# header = item.find('h3', class_='p-small-bold')
# percentage = item.find('h3', class_='h5')
# if header and percentage:
# strengths[header.text.strip()] = percentage.text.strip()
# return strengths
# return None
# url = 'https://www.kununu.com/de/search?country=de&location=city-2fbd1016-893c-4ef0-bea2-7e709129d312'
# url_company = f"https://www.kununu.com/de/deutsche-post/kultur"
# # company_urls_json = scrape_company_urls(url)
# company_strengths = scrape_company_strengths(url_company)
# print(company_strengths)
# # print(company_urls_json)
def scrape_company_factors(url_company):
response = requests.get(url_company)
if response.status_code != 200:
print(f"Failed to retrieve page. Status code: {response.status_code}")
return None
soup = BeautifulSoup(response.content, 'html.parser')
factors = {'Strengths': {}, 'Weaknesses': {}}
sections = soup.find_all('section', class_='index__topFactorList__J8yDG')
print(sections)
if sections:
for section in sections:
heading = section.find('h3', class_='index__topFactorHeading__jpBhA')
if heading:
category = 'Strengths' if 'Strengthen' in heading.text else 'Weaknesses'
for item in section.find_all('li', class_='index__container__yePeh'):
header = item.find('h3', class_='p-small-bold')
percentage = item.find('h3', class_='h5')
if header and percentage:
factors[category][header.text.strip()] = percentage.text.strip()
return factors
url_company = f"https://www.kununu.com/de/deutsche-post/kultur"
company_factors = scrape_company_factors(url_company)
print(company_factors)
User:
Based on the given div above, write a scraping code that fetches the strengths and weaknesses which are the in the class "index__topFactorList__J8yDG". Both have the same class but different sections, so find a solution to get results from both sections. Also note, that they are under a tab with the heading "Stärken & Schwächen", which needs to be clicked to show the other similar section.
Assistant:
To scrape both the strengths and weaknesses from the given HTML div, you need to achieve a few things:
Simulate clicking on the "Stärken & Schwächen" (Strengths & Weaknesses) tab to make JavaScript content visible. This often requires using a tool like Selenium, which can interact with a web page the way a browser does.
Parse the structured data of strengths and weaknesses once the DOM is updated with the visible content.
Differentiate between the two sections, even if they have the same CSS class.
Here's how you can implement this in Python using Selenium to handle dynamic content:
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
def scrape_strengths_and_weaknesses(url):
# Set up the Selenium web driver
service = Service('/path/to/chromedriver') # Update with your chromedriver path
driver = webdriver.Chrome(service=service)
try:
# Navigate to the page
driver.get(url)
time.sleep(2) # Wait for the page to load completely
# Find and click the "Strengths & Weaknesses" tab
strengths_and_weaknesses_tab = driver.find_element(By.ID, "strengthsAndWeaknessesTabBtn")
strengths_and_weaknesses_tab.click()
time.sleep(2) # Wait for the content to refresh
# Now parse the updated HTML content using BeautifulSoup
soup = BeautifulSoup(driver.page_source, 'html.parser')
# Find all sections with class 'index__topFactorList__J8yDG'
sections = soup.find_all('section', class_='index__topFactorList__J8yDG')
factors = {'Strengths': {}, 'Weaknesses': {}}
for section in sections:
# Check the text of the heading to determine if it's strengths or weaknesses
heading = section.find('h3', class_='index__topFactorHeading__jpBhA').text.strip()
if 'Strengthen' in heading:
category = 'Strengths'
elif 'Weaken' in heading:
category = 'Weaknesses'
else:
continue
# Iterate over list items and extract data
for item in section.find_all('li', class_='index__container__yePeh'):
header = item.find('h3', class_='p-small-bold').text.strip()
percentage = item.find('h3', class_='h5').text.strip()
factors[category][header] = percentage
return factors
finally:
driver.quit()
url_company = 'https://example.com/path-to-page' # Update with the actual URL
company_factors = scrape_strengths_and_weaknesses(url_company)
print(company_factors)
Notes:
Selenium: Used for handling JavaScript-rendered content that requires interaction such as clicking on a tab.
BeautifulSoup: Used for parsing and extracting the required data once the page content has been loaded and made visible.
Pauses (time.sleep): These pauses are necessary to ensure that the changes brought about by clicking the tab have been fully rendered before attempting to extract data. In real implementations, more sophisticated waits like WebDriverWait could be used to wait for specific elements to be present.
Ensure you have the correct driver installed for your browser version. Adjust paths and imports based on your environment and setup.
Replace /path/to/chromedriver and 'https://example.com/path-to-page' with the actual path to your ChromeDriver and the URL you want to scrape, respectively.