Python中的Selenium - 打开下拉菜单中的每个链接

时间:2016-10-10 20:46:32

标签: python selenium

我是Python的新手,但我一直在寻找过去一小时关于如何做到这一点,这个代码几乎可以工作。我需要在折叠(下拉菜单)菜单中打开每个类别,然后按Ctrl + t现在.active类中的每个链接。浏览器打开,所有类别也打开,但我没有在新标签中打开任何.active链接。我将不胜感激任何帮助。

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

driver = webdriver.Firefox()
driver.get("pioneerdoctor.com/productpage.cfm")

cat = driver.find_elements_by_css_selector("a[href*='Product_home']")

for i in cat:
    i.click()
    child = driver.find_elements_by_css_selector("li.active > a[href*='ProductPage']")
    for m in child:
        m.send_keys(Keys.CONTROL + 't')

编辑:

这是我通过写入文本文件并使用webbrowser来实现的当前解决方法。我看到的唯一问题是它多次重复写入结果。我稍后会仔细阅读这些评论,看看能否以更好的方式使用它(我确信有)。

from selenium import webdriver
import webbrowser

print("Opening Google Chrome..")
driver = webdriver.Chrome()
driver.get("http://pioneerdoctor.com/productpage.cfm")
driver.implicitly_wait(.5)
driver.maximize_window()

cat = driver.find_elements_by_css_selector("a[href*='Product_home']")

print("Writing URLS to file..")
for i in cat:
    i.click()
    child = driver.find_elements_by_css_selector("a[href*='ProductPage']")

    for i in child:
        child = i.get_attribute("href")
        file = open("Output.txt", "a")
        file.write(str(child) + '\n')
        file.close()

driver.quit
file = open("Output.txt", "r")

Loop = input("Loop Number,  Enter 0 to quit:  ")
Loop = int(Loop)
x = 0

if Loop == 0:
    print("Quitting..")
else:
    for z in file:
        if x == Loop:
            break
            print("Done.\n")
        else:
            webbrowser.open_new_tab(z)
            x += 1

1 个答案:

答案 0 :(得分:0)

找不到这些类别中的任何链接,因为链接的css选择器不正确。移除>中的li.active > a[href*='ProductPage']。为什么? p > q为你提供p的直接孩子。空间或" p q"给你所有的" q"在里面您感兴趣的链接不是李的直接子女。它们位于li内部的UL内。

另一个问题是您在新标签页中打开链接的方式。请改用此代码:

combo = Keys.chord(Keys.CONTROL, Keys.RETURN)
m.sendKeys(combo)

这就是我在Java中的表现。我认为python应该有Keys.chord。如果我是你,那么我会在另一个浏览器实例中打开链接。我已经看到selenium本身不支持在标签和窗口之间切换。坏事可能发生。

在尝试任何标签之前,举一个简单的例子来打开一个新标签并切换回上一个标签。来回做3-4次。它运作顺畅吗?好。然后,使用3-5个选项卡执行此操作。告诉我你的经历如何。