【问题标题】:how to loop thorough a listing in selenium webdriver如何遍历 selenium webdriver 中的列表
【发布时间】:2015-09-30 12:37:27
【问题描述】:

我正在尝试遍历包含公司列表的目录。我已经用 selenium 编写了这段代码,它只会打开一个链接。我想像新标签中的每个链接一样打开并抓取一些信息。

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


browser = webdriver.Firefox() # Get local session of firefox

# 0 wait until the pages are loaded
browser.implicitly_wait(3) # 3 secs should be enough. if not, increase it

browser.get("http://ae.bizdirlib.com/taxonomy/term/1493") # Load page

link = browser.find_element_by_css_selector("h2 > a")
links.click()

这段代码怎么不会打开下一个链接。当我尝试遍历 link.click() 时,它给了我一个错误,例如“无法遍历 web 元素”

selenium web 驱动程序的新手。有人可以帮助我为我增强代码。

【问题讨论】:

    标签: python-2.7 selenium selenium-webdriver


    【解决方案1】:

    不要使用find_element_by_css_selector,而是使用find_elements_by_css_selector。这允许选择多个元素。

    然后使用for循环进行迭代。

    links = browser.find_elements_by_css_selector("h2 > a")
    for link in links:
        link.click()
    

    要在新选项卡中打开链接而不是 link.click(),请使用 link.send_keys(Keys.CONTROL + Keys.RETURN)

    没有直接的方法可以打开新标签或在它们之间遍历。您必须使用浏览器的键盘快捷键才能使用它。

    有关find_elements_by_css_selector 的文档,请参阅here

    【讨论】:

    • 好吧,我还想做一件事,打开我在新标签页中复制的链接,然后对它进行一些网络抓取。问题是我无法在新标签中打开链接。大量链接可用于打开空白选项卡。但没有可用于打开链接的资源。
    • @PythonLearner - 要在新选项卡中打开链接,请尝试使用 link.send_keys(Keys.CONTROL + Keys.RETURN) 而不是 link.click()
    • @JRodDynamite 这是我的问题。你能帮我吗stackoverflow.com/questions/43232248/…
    【解决方案2】:

    使用link = browser.find_element_by_css_selector("h2 > a") 将只返回一个元素来获取您应该使用links = browser.find_elements_by_css_selector("h2 > a") 的元素列表。 然后对其进行迭代。

    请在下面找到这两个问题的完整答案:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.Firefox() # Get local session of firefox
    
    # 0 wait until the pages are loaded
    driver.implicitly_wait(3) # 3 secs should be enough. if not, increase it
    
    driver.get("http://ae.bizdirlib.com/taxonomy/term/1493") # Load page
    parent_tab = driver.current_window_handle
    print parent_tab
    
    links = driver.find_elements_by_css_selector("h2 > a")
    
    for link in links:
        body = driver.find_element_by_tag_name("body")
        body.send_keys(Keys.CONTROL + 't')
        driver.get(link.get_attribute('href'))
        driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + Keys.NUMPAD1)
        driver.switch_to_window(parent_tab)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多