我在执行我的Python程序时遇到以下错误,该程序试图将href元素添加到基本URL以形成下一页的URL:
“TypeError:无法连接'str'和'FirefoxWebElement'对象”
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
my_url = 'http://cbseaff.nic.in/cbse_aff/schdir_Report/userview.aspx'
browser.get(my_url)
radio_key_word = browser.find_element_by_id("optlist_0")
radio_key_word.click()
time.sleep(6)
search = browser.find_element_by_id('keytext')
search.send_keys('0')
search.send_keys(Keys.RETURN)
search.clear()
time.sleep(6)
initial_url = 'http://cbseaff.nic.in/cbse_aff/schdir_Report/'
# links = browser.find_elements_by_xpath('//tr/td/a/@href')
links = browser.find_elements_by_xpath("//tr/td/a/@href")
print len(links)
for link in links:
# print str(link)
new_url = initial_url + link
print new_url
browser.close()
这是我在执行时遇到的错误:
C:\Python27\python.exe C:/Python_project/8_March_2017/test_subject.py
Traceback (most recent call last):
25
File "C:/Python_project/8_March_2017/test_subject.py", line 30, in <module>
new_url = initial_url + link
TypeError: cannot concatenate 'str' and 'FirefoxWebElement' objects
答案 0 :(得分:2)
您得到的错误不是硒错误。而是一个简单的python字符串连接与非字符串对象。 find_elements_by_xpath
为您提供WebElement对象列表,而<web_element>.get_attribute("attribute")
为您提供字符串对象。
由于您希望获取href而不是文本,因此您可以尝试获取该属性。
links = driver.find_elements_by_xpath('//div/tr/td/a')
for link in links:
new_url = base_url + link.get_attribute("href")
答案 1 :(得分:0)
我设法纠正了代码,以正确的格式获取'href'。谢谢Yeo。以下是我所做的相同更改的代码。
link = browser.find_element_by_id(test1).get_attribute("href")
print link
现在我能够得到正确的输出:
http://cbseaff.nic.in/cbse_aff/schdir_Report/AppViewdir.aspx?affno=930305
http://cbseaff.nic.in/cbse_aff/schdir_Report/AppViewdir.aspx?affno=530382