作者obelisk0114 (追风筝的孩子)
看板Python
标题[问题] Selenium 登入论坛
时间Mon Apr 25 21:23:02 2016
使用 Selenium 和 Chrome 的 webdriver 来试着写自动登入论坛的程式
不过有些论坛使用 javascript 弹出登入视窗的方式,不知如何定位
ex1: 伊莉讨论区
登录和注册部分的网页原始码
<span class="pipe">|</span>
<a href="member.php?mod=register">注册</a>
<span class="pipe">|</span>
<a href="javascript:;" onclick="lsSubmit()">登录</a>
ex2: 卡提诺论坛
<a href="javascript:;" id="umenu" class="active"><span
class="userIcon"></span></a>
-----
我使用的程式码分为三部分: 进入网页, 点击登录, 输入帐号密码
# 点击登录
def loginClick(uri, acc, password):
regex = re.compile('user', re.IGNORECASE)
condition = False
for link in driver.find_elements_by_xpath("//a[@href=\"javascript:;\"]"):
if (link.text == '登录' ):
link.click()
condition = True
break
elif (regex.search(str(link.find_element((By.XPATH, "..")))) != None):
link.click()
condition = True
break
if (condition == False):
print('特殊情况, 无法定位点击')
print(uri)
# 输入帐号密码
def login_username(uri, acc, password):
account = driver.find_element_by_xpath("//input[@name='username']")
account.clear()
account.send_keys(acc)
pwd = driver.find_element_by_xpath("//input[@type='password']")
pwd.clear()
pwd.send_keys(password)
driver.find_element_by_xpath("//form[@method='post']").submit()
# 进入网页
def execute():
URI = '
http://ck101.com/' # 或是伊莉讨论区
data = driver.get(URI)
try:
element = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH,"//input[@type='password']")))
except TimeoutException:
print(URI + ' Load page timeout.')
else:
try:
login_username(URI, 我的帐号, 我的密码)
except:
loginClick(URI, 我的帐号, 我的密码)
login_username(URI, 我的帐号, 我的密码)
execute()
执行後会出现
InvalidSelectorException: Invalid locator values passed in
连 '特殊情况, 无法定位点击' 都没有印出
不知道是不是弹出视窗那边出现新的事件没被抓到 ?
--
│ ███ ▂▄▃
││││
│ ˋ ◤Mooncat~◥││││ 「为什麽
,
│ ‵ ◤ ◥▏*_▂▁ ▋
│││ 为什麽教授这麽靠盃
│ ′ 、▌█
▊▉▏ │ 没天理啊
……
…」
◢ ◤◢
◣▋◢ █
▋▊ ▕▅▇
◥◥*Mooncat~
◢ ▂▇ˋ█▆◤
▂_ ▁▄▆▇▃ by mooncats
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.112.25.105
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1461590592.A.A8E.html
1F:→ MOONY135: Selenium 用火狐的测试产出PYTHON 2.X版的CODE再修改 04/25 22:54
2F:→ MOONY135: 会比较方便 04/25 22:54
特地装了 Selenium IDE 来测试, 结果跟我的思路一样, 没找到问题
※ 编辑: obelisk0114 (140.112.25.105), 04/26/2016 18:09:27
伊莉讨论区的部分
elif 那边好像有点问题, 注解掉就成功点击了
但是会跑出另一个错误
Element is not currently interactable and may not be manipulated
※ 编辑: obelisk0114 (140.112.25.105), 04/26/2016 19:41:46
3F:→ s860134: 既然会用 except 去抓例外 你可以插几个去抓哪里错 04/27 07:49
※ 编辑: obelisk0114 (140.112.25.105), 05/02/2016 14:16:39