通过 Python 中的网络抓取工具登录网站
Posted
技术标签:
【中文标题】通过 Python 中的网络抓取工具登录网站【英文标题】:Login to a website through web-scraping tool in Python 【发布时间】:2012-01-08 10:23:55 【问题描述】:我在 Python 中使用 Selenium webdriver 进行网页抓取项目。
我想通过输入登录详细信息进行登录,然后单击提交按钮。
我可以输入用户名和密码。但是我不能用鼠标点击提交按钮。
“提交”按钮的类型为<input>
。
<input type="image" src="/images/buttons/loginnow.gif" tabindex="3">
这是我试图点击鼠标的python代码。
submitButton=driver.find_element_by_xpath("//input[@type='image'][@src='/images/buttons/loginnow.gif']")
driver.click(submitButton)
我收到以下错误:
AttributeError: 'WebDriver' 对象没有属性 'click'
知道如何修复它或使用 Python 登录网站的任何其他替代解决方案。
谢谢
【问题讨论】:
【参考方案1】:我很幸运使用mechanize
。它非常简单易用。
这是我编写的脚本的精简版:
from BeautifulSoup import BeautifulSoup
from tidylib import tidy_document
import mechanize
import cookielib
if __name__ == '__main__':
browser = mechanize.Browser()
cookiejar = cookielib.LWPCookieJar()
browser.set_cookiejar(cookiejar)
browser.set_handle_equiv(True)
browser.set_handle_redirect(True)
browser.set_handle_referer(True)
browser.set_handle_robots(False)
browser.open('https://www.example.com/')
browser.select_form(name = 'loginform')
browser['username'] = 'foo'
browser['password'] = 'bar'
browser.submit()
browser.open(browser.click_link(text = 'Link text'))
soup = BeautifulSoup(tidy_document(browser.response().read())[0])
您真的不需要点击图片。您只需填写所有适当的表格详细信息,然后submit()
即可。
另外,如果您不解析任何内容,只需摆脱 BeautifulSoup
和 tidylib
依赖项即可。
【讨论】:
Vow.. 这真是太神奇了,事实证明,Selenium 也有submit()
对我有用
重写你的脚本更好:P【参考方案2】:
你需要调用元素的点击函数,而不是驱动。
submitButton=driver.find_element_by_xpath("//input[@type='image'][@src='/images/buttons/loginnow.gif']")
submitButton.click()
【讨论】:
以上是关于通过 Python 中的网络抓取工具登录网站的主要内容,如果未能解决你的问题,请参考以下文章