在try循环中检查属性时出现硒错误

时间:2019-02-19 07:57:37

标签: python selenium web-scraping

url='https://relatedwords.org/relatedto/music'
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626'}
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver=webdriver.Chrome(executable_path="/home/timmy/Python/chromedriver",chrome_options=options)
driver.get(url)
MAXIMUM_NUMBER=8
MINIMUM_NUMBER=0
ListWords=[]
for i in driver.find_elements_by_xpath('//a[@id=""]'):
    try:
        i=i.get_attribute("href").split("/")[-1]
        if "%20"in i:
            i=i.replace("%20"," ")
        ListWords.append(i)
        print("New Word added to our database:  %s"%i
    except:
        pass

    MINIMUM_NUMBER+=1
    if MINIMUM_NUMBER==MAXIMUM_NUMBER:
        break

print(ListWords)

当我运行此代码时,出现以下错误

  File "/home/timmy/Python/1.py", line 18
    except:
         ^
SyntaxError: invalid syntax

我不确定为什么我尝试了它的语法错误

except Exception as e: pass,但是没有用 该程序的目的是从网站上以代码形式获取前8个相关单词并将其存储在ListWords中 谁能告诉我我在做什么错,以及如何解决?

2 个答案:

答案 0 :(得分:1)

您忘记关闭方括号。更改

 print("New Word added to our database:  %s"%i)

答案 1 :(得分:1)

您错过了)行中的print("New Word added to our database: %s"%i