ChatGPT解决这个技术问题 Extra ChatGPT

Python Selenium 访问 HTML 源代码

如何使用带有 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 源代码。

在 if 条件之前写下以下行: html_source = browser.page_source

B
Boris Verkhovskiy

您需要访问 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

迄今为止最好的答案!执行此操作的最直接和最清晰的方法,比其他仍然有效的替代方法 (find_element_by_xpath("//*").get_attribute("outerHTML")(
如果我们需要在所有 javascript 执行后获取页面源代码怎么办?
仅在页面已完全加载时才有效。如果页面无限加载,则此属性不起作用。
M
Mobin Al Hassan
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 函数来提取数据...


D
Dhiraj

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:

虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高答案的长期价值。
M
Milanka

使用 Selenium2Library,您可以使用 get_source()

import Selenium2Library
s = Selenium2Library.Selenium2Library()
s.open_browser("localhost:7080", "firefox")
source = s.get_source()

我可以设置延迟并获取最新源吗?有使用 javascript 加载的动态内容。
A
Asclepius

通过使用页面源,您将获得整个 HTML 代码。因此,首先确定您需要在其中检索数据或单击元素的代码块或标记。

options = driver.find_elements_by_name_("XXX")
for option in options:
    if option.text == "XXXXXX":
        print(option.text)
        option.click()

您可以按名称、XPath、id、链接和 CSS 路径查找元素。


S
SysMurff

您可以简单地使用 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...')

这个答案与 stackoverflow.com/a/7866938/2231972 有何不同?
P
Peter Mortensen

要回答有关让 URL 用于 urllib 的问题,只需执行以下 JavaScript 代码:

url = browser.execute_script("return window.location;")

P
Peter Mortensen

我建议使用 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.

好的,那么您知道我如何在 Selenium 中获取 URL 吗?我想将 URL 存储在一个变量中,以便我可以使用 urllib 访问它。
@user1008791 这有关系吗?您显然是让用户使用 raw_input 输入它,只是使用 urllib 做同样的事情。
那只是为了做一个简单的例子,URL 会发生很大的变化。
Selenium 做了很多 urllib 没有做的事情(例如执行 JavaScript)。
在这里使用 urllib 是没有意义的,为什么? AutomatedTester 是正确的,这是我扫描 HTML 源代码以确保我们不会推送开发环境代码。