今天练习的是新闻内容局部抓取,不需要打印全文,只需要打印前面两三段,所以可以直接定位到前三段的p标签
content1=driver.find_element_by_xpath("//*[@id='newsmain-ej']/div/div[1]/div[1]/div[4]/div/p[1]").text
content2=driver.find_element_by_xpath("//*[@id='newsmain-ej']/div/div[1]/div[1]/div[4]/div/p[2]").text
content3=driver.find_element_by_xpath("//*[@id='newsmain-ej']/div/div[1]/div[1]/div[4]/div/p[3]").text
但是实际抓取的时候有一篇文章报错了,因为它很短,没有第三段——selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:
于是想到能不能用try-except来处理异常,判断有没有第三段。查了一下确实有这个异常NoSuchElementException,要用到这个NoSuchElementException异常,要在开头导入from selenium.common.exceptions import NoSuchElementException。
如果没有第三段,也就是说p[3]不存在,那就只打印第一和第二段,如果没有异常,则打印前三段: