学习思路:
查看github项目的源码,每个方法都有介绍及使用说明
https://github.com/mherrmann/selenium-python-helium/blob/master/helium/__init__.py
Starting a browser # 打开浏览器
Helium currently supports Chrome and Firefox. You can start them with the following functions:
start_chrome() # 打开chrome浏览器
start_firefox() # 打开火狐浏览器
You can optionally pass a URL to open (eg. start_chrome('google.com'))
Headless browser
When you type the above commands, you will actually see a browser window open. This is useful for developing your scripts. However, once you run them, you may not want this window to appear. You can achieve this by adding headless=True
:
start_chrome(headless=True)
start_chrome('google.com',headless=True)
(Similarly for start_firefox(...)
of course.)
Interacting with a web site # 与web交互
The following example shows the most typical statements in a Helium script:
from helium import *
start_chrome('google.com')
write('helium selenium github')
press(ENTER)
click('mherrmann/helium')
go_to('github.com/login')
write('username',into='Username')
write('password',into='Password')
click('Sign in')
kill_browser()
Most of your own code will (hopefully) be as simple as the above.
Element * # 元素类型
The above example used pure strings such as Sign in
to identify elements on the web page. But Helium also lets you target elements more specifically. For instance:
Link('Sign in')
Button('Sign in')
TextField('First name')
CheckBox('I accept')
RadioButton('Windows')
Image(alt='Helium logo')
You can pass them into other functions such as click(Link('Sign in'))
. But you can also use them to read data from the web site. For instance:
A common use case is to use .exists()
to check for the existence of an element. For example:
if Text('Accept cookies?').exists():
click('I accept')
I also often find Text(...).value
useful for reading out data:
name = Text(to_right_of='Name:',below=Image(alt='Profile picture')).value
For a full list of element * and their properties, please see the source code.
举例:
click
def click(element):
"""
:param element: The element or point to click.
:type element: str, unicode, :py:class:`HTMLElement`, \
:py:class:`selenium.webdriver.remote.webelement.WebElement` or :py:class:`Point`
Clicks on the given element or point. Common examples are::
click("Sign in")
click(Button("OK"))
click(Point(200, 300))
click(ComboBox("File type").top_left + (50, 0))
"""
Text
class Text(HTMLElement):
"""
Lets you identify any text or label on a web page. This is most useful for
checking whether a particular text exists::
if Text("Do you want to proceed?").exists():
click("Yes")
``Text`` also makes it possible to read plain text data from a web page. For
example, suppose you have a table of people's email addresses. Then you
can read John's email addresses as follows::
Text(below="Email", to_right_of="John").value
Similarly to ``below`` and ``to_right_of``, the keyword parameters ``above``
and ``to_left_of`` can be used to search for texts above and to the left of
other web elements.
"""