Skip to main content
 首页 » 编程设计

python之如何将 FirefoxWebElememt 转换为字符串类型

2024年10月01日2398°冷暖

我在执行我的 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 

请您参考如下方法:

您得到的错误不是 selenium 错误。而是一个简单的 python 字符串与非字符串对象的连接。 find_elements_by_xpath <web_element>.get_attribute("attribute") 为您提供 WebElement 对象列表给你字符串对象。

既然你想获取 href 而不是文本,你可以尝试获取属性。

links = driver.find_elements_by_xpath('//div/tr/td/a') 
for link in links: 
    new_url = base_url + link.get_attribute("href") 

引用:selenium.WebElement.get_attribute