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

标签 python selenium-webdriver web-scraping

我在执行 Python 程序时遇到以下错误,该程序尝试将 href 元素添加到基本 URL 以形成下一页的 URL:

“类型错误:无法连接‘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为您提供 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")

引用:selenium.WebElement.get_attribute

关于python - 如何将FirefoxWebElememt转换为字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685132/

相关文章:

python - Python 列表中的位置

python - PyQt5:通过单击 QPushButton 画一条线

python - 如何在 24 小时内从动态加载的网页中抓取超过 50,000 个数据点?

python - 如何在 Python/BS4 中向我的网页抓取脚本添加代理和 header ?

python - 将字节串发送到串口设备

python - 为什么我的自定义 lightgbm 损失没有减少?

java - 如何使用 selenium web 驱动程序绕过/允许 safari mac 中的相机选项?

c# - 使用 Selenium 使用 WindowHandles 跟踪和迭代选项卡和窗口的最佳方法

java - 将表中的多个 UI 元素放入数组中

python - 使用 requests_html 和 pyppeteer python 发送点击