Python Selenium 访问 HTML 源代码
- 2025-02-17 09:24:00
- admin 原创
- 61
问题描述:
如何使用 Python 中的 Selenium 模块获取变量中的HTML源?
我想做这样的事:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://example.com")
if "whatever" in html_source:
# Do something
else:
# Do something else
我该怎么做?我不知道如何访问 HTML 源代码。
解决方案 1:
您需要访问该page_source
属性:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://example.com")
html_source = browser.page_source
if "whatever" in html_source:
# do something
else:
# do something else
解决方案 2:
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')
现在您可以应用 BeautifulSoup 函数来提取数据...
解决方案 3:
driver.page_source将帮助您获取页面源代码。您可以检查文本是否存在于页面源代码中。
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
print('Found it!')
else:
print('Did not find it.')
如果要将页面源存储在变量中,请在driver.get后添加以下行:
var_pgsource=driver.page_source
并将if条件更改为:
if "your text here" in var_pgsource:
解决方案 4:
使用 Selenium2Library 您可以使用get_source()
import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()
解决方案 5:
通过使用页面源代码,您将获得完整的 HTML 代码。
因此,首先确定需要检索数据或单击元素的代码块或标签。
options = driver.find_elements_by_name_("XXX")
for option in options:
if option.text == "XXXXXX":
print(option.text)
option.click()
您可以通过名称、XPath、id、链接和 CSS 路径找到元素。
解决方案 6:
要回答有关获取用于 urllib 的URL 的问题,只需执行以下 JavaScript 代码:
url = browser.execute_script("return window.location;")
解决方案 7:
您可以简单地使用该对象,并通过其字段WebDriver
访问页面源代码...@property
`page_source`
尝试一下此代码片段:-)
from selenium import webdriver
driver = webdriver.Firefox('path/to/executable')
driver.get('https://some-domain.com')
source = driver.page_source
if 'stuff' in source:
print('found...')
else:
print('not in source...')
解决方案 8:
完整代码:
from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome() # Use the appropriate WebDriver for your browser
# Navigate to the desired URL
driver.get("https://www.example.com/")
# Access the page's HTML source
html_source = driver.page_source
if "whatever" in html_source:
# do something
else:
# do something else
# if you want to display complete source code.
print(html_source)
# Close the WebDriver
driver.quit()
解决方案 9:
我建议使用urllib获取源代码,如果要解析,请使用类似Beautiful Soup之类的东西。
import urllib
url = urllib.urlopen("http://example.com") # Open the URL.
content = url.readlines() # Read the source and save it to a variable.
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD