Python Selenium打印元素的空innerHTML/innerText
对于Selenium,为什么下面的函数会打印空字符串?如果我尝试使用Python Selenium打印元素的空innerHTML/innerText,python,html,selenium,web-scraping,Python,Html,Selenium,Web Scraping,对于Selenium,为什么下面的函数会打印空字符串?如果我尝试使用'innerText'而不是'innerHTML',则相同 send_key部件工作正常 def button_clicked(self): browser = webdriver.Firefox() browser.get('https://www.google.com') search_box = browser.find_element_by_xpath("//input[@
'innerText'
而不是'innerHTML'
,则相同
send_key
部件工作正常
def button_clicked(self):
browser = webdriver.Firefox()
browser.get('https://www.google.com')
search_box = browser.find_element_by_xpath("//input[@title='Search']")
search_box_HTML = search_box.get_attribute('innerHTML')
print(search_box_HTML)
您应该将代码更改为:
search_box.get_attribute('value')
这应该可以做到一个
没有内部内容文本或HTML。相反,用户输入的数据存储在其值
属性中,可以使用WebElement#get_attribute()
检索该属性:
搜索框。获取属性(“值”)
如果您查看页面的HTML并检查搜索框,您已将其标识为:
find_element_by_xpath("//input[@title='Search']")
WebElement的定义如下:
<input class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Search" type="text" value="" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="list" dir="ltr" spellcheck="false" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; background: url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") transparent; position: absolute; z-index: 6; left: 0px; outline: none;">
def get_attribute(self, name):
"""Gets the given attribute or property of the element.
This method will first try to return the value of a property with the
given name. If a property with that name doesn't exist, it returns the
value of the attribute with the same name. If there's no attribute with
that name, ``None`` is returned.
Values which are considered truthy, that is equals "true" or "false",
are returned as booleans. All other non-``None`` values are returned
as strings. For attributes or properties which do not exist, ``None``
is returned.
:Args:
- name - Name of the attribute/property to retrieve.
Example::
# Check if the "active" CSS class is applied to an element.
is_active = "active" in target_element.get_attribute("class")
"""
因此,由于WebElement(即搜索框)没有后代,因此
get\u属性('innerHTML')
返回空您可以总结一下您试图自动执行的手动步骤吗?此代码只是将print语句放在某些上下文中。我感兴趣的是为什么internal
HTML`和innerText
在Selenium中不能与Python一起工作。例如,当通过VBA自动化IE时,我可以使用getAttribute(“innerHTML”)
打印innerHTML
,而不会对innerText()
发表评论,但是getAttribute(“innerHTML”)
经过验证,功能强大,在适当的上下文中使用时可以正常工作。然而,我不理解代码中的/xpathfind_element\u by_xpath(//input[@title='Szukaj'])
行,同时我也看不到代码中textbox
的上下文。我删除了与问题无关的“textbox”行find\u element\u by_xpath(“//input[@title='Search'])
在Google上找到输入框。我想打印它的innerHTML
@barciewicz,为将来读者的利益,把这个/任何对你有用的答案都投上一票。