我对Python非常陌生。我正在尝试写一个程序,它将接受一个IP地址,并使用https://community.spiceworks.com/tools/ip-lookup/上的搜索功能来搜索该IP并将结果返回给我。
我写了以下内容:
import selenium.webdriver as webdriver
def get_results(search_term):
url = "https://community.spiceworks.com/tools/ip-lookup/"
browser = webdriver.Firefox()
browser.get(url)
search_box = browser.find_element_by_id("ipaddress")
search_box.send_keys(search_term)
search_box.submit()
try:
tables = browser.find_element_by_class("in-card detail-list ember-view")
results = []
for table in tables:
print(table)
results.append(table)
browser.close()
return results
print(results)
get_results("137.2.167.117")(我使用了一个随机的IP地址)当我运行这个命令时,我得到:
results = [] (with an arrow pointing to the "s" in results) SyntaxError: invalid syntax我写的代码是正确的吗?是什么导致了这个错误?我是否正确地使用了搜索功能和结果?搜索这个并没有返回太多的结果。谢谢!
发布于 2018-02-27 10:15:46
根据语言的定义,try块后面必须跟except或finally:https://docs.python.org/3/reference/compound_stmts.html#try
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> try:
... print("foo")
... results = []
File "<stdin>", line 3
results = []
^
SyntaxError: invalid syntax您的代码失败的原因与上面的代码片段相同,下一条语句(results)既不是except也不是finally。
发布于 2018-02-27 10:14:46
我没有时间尝试运行代码,因为我目前没有selenium库,但将其粘贴到Pycharm中会突出几个问题:
对于返回,您需要为try
except try失败,表将不会被定义,并且在返回将永远不会到达之后在for loop
print(results)中读取它时会导致问题导致语法错误的原因是缺少except。前两个问题的快速解决方案是:
try:
tables = browser.find_element_by_class("in-card detail-list ember-view")
except:
tables = []https://stackoverflow.com/questions/49000008
复制相似问题