【问题标题】:How to convert FirefoxWebElememt into string type?如何将 FirefoxWebElememt 转换为字符串类型?
【发布时间】:2017-03-09 01:40:18
【问题描述】:

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

【问题讨论】:

  • 您肯定需要提供更多信息,包括您正在执行的 HTML 以及您正在尝试做什么。
  • 我已经更新了问题,你现在可以检查一下吗?

标签: python selenium-webdriver web-scraping


【解决方案1】:

您得到的错误不是 selenium 错误。而是一个简单的 python 字符串连接与非字符串对象。 find_elements_by_xpath 为您提供 WebElement 对象列表,而 &lt;web_element&gt;.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")

参考:selenium.WebElement.get_attribute

【讨论】:

  • 在进行上述更改时,我收到一个新错误:Traceback (most recent call last): File "C:/Python_project/8_March_2017/test_subject.py", line 28, in &lt;module&gt; for link in links.get_attribute("href"): AttributeError: 'list' object has no attribute 'get_attribute'
  • 抱歉,我忘了提到 get_attribute 是用于 WebElement 对象,而 find_elements 为您提供 WebElement 列表。所以我已经相应地更新了我的答案
【解决方案2】:

我设法更正了代码以获取正确格式的“href”。感谢叶。以下是我所做的相同更改的代码。

 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

【讨论】:

    猜你喜欢
    • 2012-09-19
    • 1970-01-01
    • 2022-08-18
    • 2019-09-10
    • 1970-01-01
    • 2019-01-21
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多