【发布时间】:2016-10-21 18:22:42
【问题描述】:
这些天我一直在使用 python 和 selenium 的 webdriver 处理个人项目,但是每次脚本加载新页面然后尝试访问时,我都会收到“过时的元素引用:元素未附加到页面文档”错误一个使用“find_element”的元素。我在这里阅读了很多关于这个问题的帖子,但似乎没有任何效果。所以请给我困惑的大脑一些启示。
代码如下:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup
#Ask User for keyword
keyword = input("Insert Product Name:")
#Open chrome browser
driver = webdriver.Chrome(executable_path=r"C:\chromedriver.exe")
#Open e-bay.com
driver.get("http://www.e-bay.com")
#Find the search text field element
search_element = driver.find_element_by_id("gh-ac")
#Clear the search text field of any data
search_element.clear()
#Type the user given keyword to the text field
search_element.send_keys(keyword)
#Hit enter key
search_element.send_keys(Keys.RETURN)
#Set number of listings on the same page (25,50,100,200)
#Find the dropdown menu element for listings per page(Wait till it shows up)
dropdown_menu_lpp = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#cbBtmElem > div > ul.sel > li > a.btn.btn-s.small.btn-ter.dropdown-toggle")))
#Mouse over the dropdown menu
actions = ActionChains(driver)
actions.move_to_element(dropdown_menu_lpp)
actions.perform()
#Find the desired setting and click it.I choose 200 listings per page here because is the most convennient for this application.
listings_per_page = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#cbBtmElem > div > ul.lyr.txtRt.dropdown-menu.dropdown-menu-sm.menu3 > li:nth-child(3)")))
actions.move_to_element(listings_per_page)
actions.click()
actions.perform()
#Find Listings link(Wait til the links show up first)
listings_links = []
listing_link_elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME,"vip")))
#Put the links in a list data-structure
for link in listing_link_elements:
listings_links.append(link.get_attribute('href'))
print(listings_links)
driver.quit()
该脚本应该打开 e-bay.com ,搜索关键字,将显示的列表数量更改为 200 ,获取(200)列表的链接并将它们放在列表数据结构中。
提前致谢。
PS:我使用的是 python 3.5。
【问题讨论】:
标签: python-3.x selenium-webdriver