python - Selenium WebDriver 停止而不打印 XPath
问题描述
我正在尝试在控制台中打印 XPath 数据。但是即使没有错误,加载第一页后该过程也会停止。
这是我的代码:
browser.get('https://stackoverflow.com/questions?pagesize=10')
while True:
try:
elm = browser.find_element_by_link_text("next")
elm.click()
labels = browser.find_element_by_xpath('/html/body/div[3]/div[2]/div[1]/div[3]/div/div/div[1]/div[2]/h3/a')
for label in labels:
print label.text
except:
break
我错过了什么?
解决方案
没有收到任何错误的原因是因为您正在捕获它们然后只是使用break。
您的问题标签的XPATH也有问题。我在链接中添加了一个滚动条next
,以防您像我一样在底部收到 cookie 通知。这是一个工作示例:
注意:这是在 Python 3 中使用当前 Chrome build 67和 chromedriver 2.40进行的测试
import traceback
from selenium.common.exceptions import NoSuchElementException
browser.get('https://stackoverflow.com/questions?pagesize=10')
while True:
try:
elm = browser.find_element_by_link_text("next")
browser.execute_script("return arguments[0].scrollIntoView();", elm)
elm.click()
labels = browser.find_elements_by_xpath('.//a[@class="question-hyperlink"]')
for label in labels:
print(label.text)
except NoSuchElementException:
print("only catching this exception now when you run out of the next elements, other exceptions will raise")
print(traceback.format_exc())
break
推荐阅读
- android - 在 ProgressBar 中显示倒数计时器的实际进度
- flutter - 具有多列和常量宽度/高度卡的列表视图
- linux - geany 不会打开终端来运行我的代码,除非打开了另一个终端窗口
- konvajs - 有什么方法可以在 Konva 上导出为 SVG
- python - Xlsxwriter Excel图表自定义数据标签位置
- reactjs - 如何从映射的输入框中禁用当前输入框
- node.js - 是否可以在不包装到函数/类中的情况下导出整个 Node.JS 模块?
- r - R:GGPLOT2:如何使用 stat_summary 在 ggplot2 的折线图中添加标签
- javascript - React Native:未定义不是对象(评估'props.navigation.navigate')
- .net - 反应中的跨源问题