python单击网页上的按钮

2024-04-23 06:02:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个脚本,登录到一个网站,我想让它点击网站上的按钮,如果它目前没有点击。以下是按钮的信息:

当按钮已激活时:

<p class="toast_btn">
    <a class="button grey toast track-click active" data-user-avatar="https://dwebsite.net/picture.jpg" data-checkin-id="123456789" data-href=":feed/toast" data-track="activity_feed" href="#">

当按钮未激活时:

<p class="toast_btn">
    <a class="button grey toast track-click" data-user-avatar="https://dwebsite.net/picture.jpg" data-checkin-id="123456789" data-href=":feed/toast" data-track="activity_feed" href="#">

我只想在class="button grey toast track-click"时单击它

最好的方法是什么?我目前使用urllib2和mechanize来登录和检查一些表单。谢谢!


Tags: httpsdata网站feedbuttontrack按钮class
1条回答
网友
1楼 · 发布于 2024-04-23 06:02:14

当我比较这两个标记时,我发现区别在于标记。 所以如果你能读的话你就完了

如果你喜欢,可以用硒来做

步骤1:查找XPath -获取按钮的XPath:在Chrome中打开页面,点击它并选择Inspect element -它将打开html文件,右键单击突出显示的行并选择copy Xpath -在记事本中复制XPath

既然已经有了XPath,就可以通过Python脚本选择按钮并查询属性

这是一个原型

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.youradress.org")#put here the adress of your page
elem = driver.find_elements_by_xpath("//*[@type='submit']")#put here the content you have put in Notepad, ie the XPath
print(elem.get_attribute("class"))
driver.close()

希望对你有帮助,如果你有问题请告诉我

我把这些链接用于文档

Python Selenium: Find object attributes using xpath

https://selenium-python.readthedocs.io/locating-elements.html

相关问题 更多 >