Python Selenium无法识别来自Google

时间:2018-04-11 18:52:29

标签: python google-chrome selenium web-scraping

嘿,我看了,测试了2到3个小时,找不到任何对我有帮助的东西。 我希望那些python类型谷歌搜索栏的东西并复制结果。

<div id="resultStats">Ungefähr 4.440.000 Ergebnisse<nobr> 
#that resultstats the text i want to copy the text which is inside ><

代码:

test = webdriver.Chrome('.\chromedriver.exe')
test.get('https://www.google.de')
test.find_element_by_id('lst-ib').send_keys('test123123')
webdriver.ActionChains(test).send_keys(Keys.ENTER).perform()
test.find_element_by_xpath('//*[@id="resultStats"]/text()').send_keys(Keys.CONTROL + 'v')

print(test)

错误:

DevTools listening on ws://127.0.0.1:12366/devtools/browser/cc7779e1-c661-4adc-91e4-067b256718db
Traceback (most recent call last):
  File "c:./niche.py", line 34, in <module>
    test.find_element_by_xpath('//*[@id="resultStats"]/text()').send_keys(Keys.CONTROL + 'v')
  File "C:.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 385, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element
    'value': value})['value']
  File "C:.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "C:.\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//*[@id="resultStats"]/text()" is: [object Text]. It should be an
element.
  (Session info: chrome=65.0.3325.181)
  (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64)

提前致谢:D

2 个答案:

答案 0 :(得分:2)

尝试使用id来定位元素:

driver.find_element_by_id('resultStats')

这是一个完整的工作示例:

from selenium import webdriver

# create your webdriver
driver = webdriver.Chrome()

# open google
driver.get('http://www.google.com')

# locate the search field
search_box = driver.find_element_by_name('q')

# type "foo" into search field
search_box.send_keys('foo')

# execute a search
search_box.submit()

# locate the resultStats element
result_stats = driver.find_element_by_id('resultStats')

# print the text of resultStats
print(result_stats.text)

这将打印:

About 27,000,000 results (0.39 seconds)

答案 1 :(得分:0)

您可以找到您的字符串并按如下方式打印:

yourText = test.find_element_by_xpath('//*[@id="resultStats"]').text

print(yourText)