【问题标题】:How fetch latest <b> tag response in selenium?如何在 selenium 中获取最新的 <b> 标签响应?
【发布时间】:2018-06-07 07:16:28
【问题描述】:

这是我的机器人:https://www.pandorabots.com/pandora/talk?botid=b3a17e933e345861

我正在尝试获取当前人类与灭霸的响应,所以我尝试了:

from selenium import webdriver
import time
driver=webdriver.Chrome()
browser=driver.get('https://www.pandorabots.com/pandora/talk?botid=b3a17e933e345861')
ask=driver.find_element_by_xpath('/html/body/form/table/tbody/tr[1]/td[1]/input')
inpu_1='ask thanos '
ask.send_keys(inpu_1)
time.sleep(2)

但现在我被卡住了,无法找到获取当前人类和灭霸响应的方法,因为标签很多,如果我尝试使用 xpath,它看起来像这样:

/html/body/b[2]

所以如果我尝试这个:

print(" thanos: {} ".format(driver.find_element_by_css_selector("b:contains('thanos:')")))

那么它什么也不给,返回空白

如何获取thanos的最新回复?

【问题讨论】:

    标签: python selenium xpath web-scraping beautifulsoup


    【解决方案1】:

    如果您观察到HTML DOM,最后一个human response 总是在top 上,最后一个thanos response 紧随其后。因此,根据您对find a way to fetch current human and thanos response 的问题,您可以使用以下代码块:

    full_text = driver.find_element_by_xpath("//body").get_attribute("innerHTML")
    one_set_conversation = full_text.split("Human:")
    human_thanos = one_set_conversation[1].split("thanos:")
    print("Last Human Reply :")
    print(human_thanos[0])
    print("Last Thanos Reply :")
    print(human_thanos[1])
    

    【讨论】:

      【解决方案2】:

      您应该只检索正文内容并处理文本内容:

      from selenium import webdriver
      import time
      driver=webdriver.Chrome()
      browser=driver.get('https://www.pandorabots.com/pandora/talk?botid=b3a17e933e345861')
      ask=driver.find_element_by_xpath('/html/body/form/table/tbody/tr[1]/td[1]/input')
      inpu_1='ask thanos '
      ask.send_keys(inpu_1)
      ask.submit()
      content = driver.find_element_by_css_selector('body').text.split("\n")
      print(content)
      time.sleep(2)
      

      此代码打印:

      ['Tell thanos:', '  Powered by Pandorabots.', '', 'Human: ask thanos', 'thanos: They are not available right now, but I will ask them later.']
      

      所以最新的响应应该是该列表的第 5 个元素。

      【讨论】:

      • 多么巧合,我做到了:P 但我使用了 driver.page_source
      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      相关资源
      最近更新 更多