82 lines
2.7 KiB
Markdown
82 lines
2.7 KiB
Markdown
# 使用示例
|
||
```python
|
||
import requests
|
||
import time
|
||
from selenium import webdriver
|
||
from selenium.webdriver.chrome.options import Options # 浏览器参数
|
||
from selenium.webdriver.common.by import By
|
||
|
||
chrome_option=Options()
|
||
# 设置浏览器参数
|
||
# chrome_option.add_argument('--headless') # 不显示图形界面,俗称无头模式
|
||
chrome_option.add_argument("--disable-gpu") # windows系统使用
|
||
# chrome_option.add_argument("--remote-debugging-port=9000")
|
||
driver=webdriver.Chrome(options=chrome_option)
|
||
# 设置网页超时时间
|
||
driver.set_page_load_timeout(60)
|
||
|
||
host="https://ag.dji.com/cn/t60/specs"
|
||
# 打开指定的网页
|
||
driver.get(host)
|
||
|
||
# 等待指定元素加载完成
|
||
WebDriverWait(driver, 10).until(
|
||
EC.visibility_of_element_located((By.ID, "player_if"))
|
||
|
||
)
|
||
|
||
# 使用 Fluent Waits 等待元素变得可见
|
||
element = FluentWait(driver, timeout=10, poll_frequency=1).until(
|
||
EC.visibility_of_element_located((By.ID, "myElement"))
|
||
)
|
||
|
||
# 使用js等待页面加载完成
|
||
wait_for_page_load = lambda: driver.execute_script("return document.readyState") == "complete"
|
||
driver.implicitly_wait(10) # 设置隐式等待时间
|
||
while not wait_for_page_load():
|
||
pass
|
||
|
||
# 使用路径查找指定的div元素的第一个内容
|
||
parameter=driver.find_element(By.XPATH,"/html/body/div[1]/div/div/div[2]/div[2]/section/div/div/div[2]/div/div/div[2]/div/div")
|
||
# 输出该元素包含的所有文本内容
|
||
print(parameter.text)
|
||
# 获取该元素的子属性
|
||
print(parameter.get_attribute("id"))
|
||
|
||
# 使用路径查找指定的div元素的所有内容,需遍历结果
|
||
parameters=driver.find_elements(By.XPATH,"/html/body/div[1]/div/div/div[2]/div[2]/section/div/div/div[2]/div/div/div[2]/div/div")
|
||
for i in parameters:
|
||
tit=i.find_elements(By.TAG_NAME, "h4")
|
||
# 多重遍历
|
||
for j in tit:
|
||
print(j.text)
|
||
# print(i.text)
|
||
|
||
# 以下是查找元素的其他方法,find_element是单数,find_elements是复数,结果是列表
|
||
# 使用标签名称查找
|
||
element = driver.find_element(By.TAG_NAME, "h3")
|
||
# 使用id名查找
|
||
element = driver.find_element(By.ID, "element_id")
|
||
# 使用name名查找
|
||
element = driver.find_element(By.NAME, "element_name")
|
||
# 使用xpath路径查找
|
||
element = driver.find_element(By.XPATH, "xpath_expression")
|
||
# 使用链接文本查找
|
||
element = driver.find_element(By.LINK_TEXT, "link text")
|
||
# 查找包含特定文本的链接
|
||
element = driver.find_element(By.PARTIAL_LINK_TEXT, "partial link text")
|
||
# 使用class类名查找
|
||
element = driver.find_element(By.CLASS_NAME, "class_name")
|
||
# 使用css选择器查找元素
|
||
element = driver.find_element(By.CSS_SELECTOR, "css_selector")
|
||
|
||
|
||
# 刷新网页
|
||
driver.refush()
|
||
|
||
# 关闭网页,如果只有一个页面,执行后等同于driver.quit()
|
||
driver.close()
|
||
|
||
# 关闭浏览器
|
||
driver.quit()
|
||
``` |