【发布时间】:2019-06-09 23:39:39
【问题描述】:
我想做什么 打开一个网址, 读取一个文本文件,一个一个地从文件中获取产品 ID, 将其输入称为网页搜索的输入字段, 点击搜索按钮, 找出页面上所有可用的供应商链接, 在新标签中打开所有供应商链接, 将这些 url 写入文件。
我尝试了什么:
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
options.add_argument("user-data-dir=d:\\abprofile")
driver = webdriver.Chrome(chrome_options=options, executable_path='C:\chromedriver_win32\chromedriver.exe')
driver.implicitly_wait(30)
driver.maximize_window()
driver.get("https://xxxxxx/products")
elem = driver.find_element_by_xpath("//input[@id='search']")
main_window = driver.current_window_handle
with open('d:/ids.txt') as in_file:
for ids in in_file:
elem.send_keys(ids)
driver.switch_to.window(main_window)
elem = driver.find_element_by_xpath("//button[contains(@id,'search')]").click()
addr = len(driver.find_elements_by_xpath("(//a[contains(.,'Available Vendors')])"))
for addrNum in range(addr):
ele = driver.find_element_by_xpath("(//a[contains(.,'Available Vendors')])[" + str(addrNum + 1) + "]")
href = ele.get_attribute('href')
driver.execute_script("window.open('" + href + "');")
time.sleep(4)
for handle in driver.window_handles:
if handle != main_window:
print(handle)
page = handle
driver.switch_to.window(page)
time.sleep(7)
element = driver.find_element_by_xpath("//a[contains(.,'Verfiy quotes')]").click()
print(driver.current_url)
urls = driver.current_url
print (urls)
with open('d:/somefile.txt', 'a') as the_file:
the_file.write(urls+"\n")
driver.switch_to.window(main_window)
但是当我从文件中提交 id 时它失败了
no such element: Unable to locate element:
{"method":"xpath","selector":"//button[contains(@id,'search')]"}
但是当我像下面这样只硬编码一个产品 id 时,它就可以工作了
工作:
elem.send_keys("34564545666")
不工作:
with open('d:/ids.txt') as in_file:
for ids in in_file:
elem.send_keys(ids)
driver.switch_to.window(main_window)
elem = driver.find_element_by_xpath("//button[contains(@id,'search')]").click()
任何建议,有什么问题......
【问题讨论】:
-
您需要等待其中的元素存在吗?对于您尝试点击的元素?
-
我相信它不是在第一次迭代中失败,而是在第二次迭代中失败。对吗?
-
是的,第二次迭代失败了