当前位置: 首页 > wzjs >正文

企业网站的建设与流程青岛贸易公司 网站制作

企业网站的建设与流程,青岛贸易公司 网站制作,seo wordpress 主题,怎样创办自己的公众号这篇文章锁定官网教程中 Examples 章节中的 Web Browser Automation with Agents文章,主要介绍了如何设计一个由Agent驱动结合视觉模态的Web内容浏览功能,包含了以下几个功能: Navigate to web pages:前往指定网页;Cl…

这篇文章锁定官网教程中 Examples 章节中的 Web Browser Automation with Agents文章,主要介绍了如何设计一个由Agent驱动结合视觉模态的Web内容浏览功能,包含了以下几个功能:

  1. Navigate to web pages:前往指定网页;
  2. Click on elements:点击网页对象;
  3. Search within pages:在页面中搜索;
  4. Handle popups and modals:处理页面弹窗内容;
  5. Extract information :抽取信息;
  • 官网链接:https://huggingface.co/docs/smolagents/v1.9.2/en/examples/web_browser;

安装以下依赖:

$ pip install smolagents selenium helium pillow -q

为了实现上面这些功能,需要完成以下步骤:

  1. 定义能够对网页进行操作的 tool,包括可以执行 Ctrl+F、后退、关闭弹窗的功能;
  2. 配置浏览器内核,官网示例中使用了 Chrmoe 浏览器内核;
  3. 定义Agent和模型;
  4. 明确操作提示词;
  5. Agnet执行操作提示词;

完整代码如下:

【注意】:官网示例中使用的是 meta-llama/Llama-3.3-70B-Instruct 模型,但这个模型的Token是需要购买的,如果这里对其进行修改像之前文章中一样使用默认分配的 Qwen-Coder 那么会在中间某一步停下来,因为默认的免费模型不支持超过 10000 Token 的输入,有条件的读者可以尝试购买一些Token实验其完整功能。

from io import BytesIO
from time import sleepimport helium
from dotenv import load_dotenv
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keysfrom smolagents import CodeAgent, tool
from smolagents.agents import ActionStep
from smolagents import HfApiModelload_dotenv()#----------------------------------------------------------------# 
# Step1. 定义网页操作tool
@tool
def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:"""Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.Args:text: The text to search fornth_result: Which occurrence to jump to (default: 1)"""elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")if nth_result > len(elements):raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")result = f"Found {len(elements)} matches for '{text}'."elem = elements[nth_result - 1]driver.execute_script("arguments[0].scrollIntoView(true);", elem)result += f"Focused on element {nth_result} of {len(elements)}"return result@tool
def go_back() -> None:"""Goes back to previous page."""driver.back()@tool
def close_popups() -> str:"""Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows!This does not work on cookie consent banners."""webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()#----------------------------------------------------------------# 
# Step2. 配置Chrome内核# Configure Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--force-device-scale-factor=1")
chrome_options.add_argument("--window-size=1000,1350")
chrome_options.add_argument("--disable-pdf-viewer")
chrome_options.add_argument("--window-position=0,0")# Initialize the browser
driver = helium.start_chrome(headless=False, options=chrome_options)# Set up screenshot callback
def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:sleep(1.0)  # Let JavaScript animations happen before taking the screenshotdriver = helium.get_driver()current_step = memory_step.step_numberif driver is not None:for previous_memory_step in agent.memory.steps:  # Remove previous screenshots for lean processingif isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:previous_memory_step.observations_images = Nonepng_bytes = driver.get_screenshot_as_png()image = Image.open(BytesIO(png_bytes))print(f"Captured a browser screenshot: {image.size} pixels")memory_step.observations_images = [image.copy()]  # Create a copy to ensure it persists# Update observations with current URLurl_info = f"Current url: {driver.current_url}"memory_step.observations = (url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info)#----------------------------------------------------------------# 
# Step3. 定义 Agent# Initialize the model
# 如果你有下面这个模型的Token则使用下面这两行代码
# model_id = "meta-llama/Llama-3.3-70B-Instruct"
# model = HfApiModel(model_id)
# 如果你只有免费的Token则使用下面这一行代码
model = HfApiModel()# Create the agent
agent = CodeAgent(tools=[go_back, close_popups, search_item_ctrl_f],model=model,additional_authorized_imports=["helium"],step_callbacks=[save_screenshot],max_steps=20,verbosity_level=2,
)# Import helium for the agent
agent.python_executor("from helium import *", agent.state)#----------------------------------------------------------------# 
# Step4. 明确操作提示词helium_instructions = """
You can use helium to access websites. Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
Code:
```py
go_to('github.com/trending')
```<end_code>You can directly click clickable elements by inputting the text that appears on them.
Code:
```py
click("Top products")
```<end_code>If it's a link:
Code:
```py
click(Link("Top products"))
```<end_code>If you try to interact with an element and it's not found, you'll get a LookupError.
In general stop your action after each button click to see what happens on your screenshot.
Never try to login in a page.To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
Code:
```py
scroll_down(num_pixels=1200) # This will scroll one viewport down
```<end_code>When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
Just use your built-in tool `close_popups` to close them:
Code:
```py
close_popups()
```<end_code>You can use .exists() to check for the existence of an element. For example:
Code:
```py
if Text('Accept cookies?').exists():click('I accept')
```<end_code>
"""search_request = """
Please navigate to https://en.wikipedia.org/wiki/Chicago and give me a sentence containing the word "1992" that mentions a construction accident.
"""#----------------------------------------------------------------# 
# Step5. Agent执行提示词
agent_output = agent.run(search_request + helium_instructions)
print("Final output:")
print(agent_output)

这里使用免费的Token执行结果如下,Agent会卡在中间的一步中,这个完全随缘,有时候刚打开网页还没有滚动就报错Token超限,有时候能滚动很多次才报错:

$ python demo.py

在这里插入图片描述

http://www.dtcms.com/wzjs/802099.html

相关文章:

  • 有关学风建设网站小红书广告投放平台
  • 广东建设工程信息网站深圳建筑设计院排名
  • 正能量不良网站直接进入免费无锡网站建设方案优化
  • 网站安全建设情况报告WordPress生成海报插件
  • seo网站营销建设网站的目的和功能定位
  • 网站建设会碰到什么问题地方门户网站还能做吗
  • 修改dns连接外国网站个人网站 虚拟主机价格
  • 汕头在线制作网站常州个人做网站
  • 佛山免费建站平台做外贸用哪些网站
  • 宁德网站开发俄文网站策划
  • 网站建设后台和前端淘宝seo搜索优化
  • 动漫网站建设目的网站设计的七个原则
  • 河南电商网站设计wordpress是cms
  • 南通通州区城乡建设局网站wordpress弹窗代码
  • 网站建设开发教程机械加工种类
  • 乌市昌吉州建设局网站网页美工设计入门详解
  • 凡客官方网站北京西站附近的景点有哪些
  • 美食网站开发的难点深圳龙岗区地图全图
  • 网站建设 慕课上杭县铁路建设办公室网站
  • 为什么上不了建设银行个人网站百度的网址怎么写
  • 永康公司网站开发北京东道设计
  • 网站模版源码邢台做网站备案
  • 可以做单的猎头网站做网站需要哪些流程
  • 永州城乡建设中等职业技术学校网站网站开发计划书范文
  • 福州一站式品牌推广运营公司展示网站系统架构设计
  • 网站报价明细现代化公司网站建设
  • 用wordpress开发网站模板重庆工程招投标交易信息网
  • 网站建设模块怎么使用服务器配置
  • 网站建设业务平均工资网站的封面怎么做
  • 小型网站项目策划书最完整的外贸流程图