Certainly! Using Selenium allows you to interact with the web page in a browser-like environment, which can be useful for scraping content from pages that rely on JavaScript rendering.
You will need to install the Selenium package and also download the appropriate driver for the browser you will be using. The example below will use the Chrome browser:
Install Selenium:Copy codepip install selenium
Download the appropriate fromhereand add it to your system's PATH.
Install Selenium:
────────────────────────────────────────────────────────────────────
Copy codepip install selenium
Download the appropriate fromhereand add it to your system's PATH.
Here is the modified script using Selenium:
────────────────────────────────────────────────────────────────────
pythonCopy codeimport random
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from bs4 import BeautifulSoup
Define a list of user agents
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.3',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36',
# Add more user agents
]
Define a pool of proxies
proxies_list = [
"proxy1.example.com:8080",
"proxy2.example.com:8080",
# Add more proxies
]
Choose random user agent and proxy
user_agent = random.choice(user_agents)
proxy = random.choice(proxies_list)
Setup Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'user-agent={user_agent}')
Setup proxy options
proxy_options = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': proxy,
'': proxy
})
Define the URL of the page you want to scrape
url =
Start the WebDriver
driver = webdriver.Chrome(options=chrome_options, desired_capabilities=proxy_options.to_capabilities())
Navigate to the URL
driver.get(url)
Get the page source
page_source = driver.page_source
Quit the driver
driver.quit()
Parse HTML using BeautifulSoup
soup = BeautifulSoup(page_source, 'html.parser')
Find script tag with type 'application/ld+json'
script_tag = soup.find('script', {'type': 'application/ld+json'})
Extract content if the tag is found
if script_tag:
content = script_tag.string
print(content)
else:
print('Script tag with type "application/ld+json" not found.')
This modified script uses Selenium to open a web browser, navigate to the specified URL, and retrieve the page source. It then parses the HTML using BeautifulSoup in the same way as the previous script, and extracts the content within thetags. Note that using Selenium is typically slower than sending HTTP requests directly (as with therequestslibrary) because it involves rendering the entire web page in a browser.