乐闻世界logo
搜索文章和话题

How can we fetch the page source in Selenium?

1个答案

1

Retrieving the page source code in Selenium is a straightforward process. We can use the page_source attribute of the WebDriver object to retrieve the HTML content of the current page. Here is a specific example demonstrating how to use Selenium in Python to retrieve page source code:

python
from selenium import webdriver # Launch Chrome browser driver = webdriver.Chrome('path to your chromedriver.exe') # Open a webpage driver.get('http://www.example.com') # Retrieve page source code page_source = driver.page_source print(page_source) # Close the browser driver.quit()

In this example, the line driver.get('http://www.example.com') opens the specified URL. After that, driver.page_source returns the source code of the page displayed in the current browser. This source code is in string format and contains the complete HTML content of the page.

This method is very useful for testing webpage content, inspecting the DOM structure, or verifying the presence of specific elements. For example, you can use this method to confirm whether an important HTML tag exists in the page after it has loaded.

Finally, remember to call driver.quit() to close the browser and release resources; this is a good programming practice.

2024年8月14日 00:02 回复

你的答案