python-3.x - 我找不到如何使用 selenium python 获取文本
问题描述
我尝试获取的内容
<span class="noactive">0 Jours restants</span>
(这是保修的到期日期)但我不知道如何获得它(我需要将它打印在一个文件中)
我的代码
def scrapper_lenovo(file, line):
CHROME_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
CHROMEDRIVER_PATH = 'C:\webdriver\chromedriver'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
d = driver.Chrome(executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options)
d.get("https://pcsupport.lenovo.com/fr/fr/warrantylookup")
search_bar = d.find_element_by_xpath('//*[@id="input_sn"]')
search_bar.send_keys(line[19])
search_bar.send_keys(Keys.RETURN)
time.sleep(4)
try:
warrant = d.find_element_by_xpath('//*[@id="W-Warranties"]/section/div/div/div[1]/div[1]/div[1]/p[1]/span')
file.write(warrant)
except:
print ("test")
pass
if ("In Warranty" not in d.page_source):
file.write(line[3])
file.write("\n")
d.close()
如您所见,我尝试打印“授权”的内容,但找不到任何允许它的功能(我看到一些使用 .text()、.gettext() 但无论出于何种原因,我都无法让它们工作)。
解决方案
您可以尝试显式匹配所需的标记,相关的 XPath 表达式将是:
//span[@class='noactive']
我还建议使用此time.sleep()
功能,它是某种形式的性能反模式,如果您需要等待某个元素的存在/可见性/不可见性/不存在,您应该使用Explicit Wait
所以删除这些行:
time.sleep(4)
warrant = d.find_element_by_xpath('//*[@id="W-Warranties"]/section/div/div/div[1]/div[1]/div[1]/p[1]/span')
并改用这个:
warrant = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//span[@class='noactive']")))
推荐阅读
- c - C中的延迟函数不延迟
- azure - 服务错误 Bot 应该使用自己的存储
- c# - C#与arduino通信(arduino不断发送数据)
- r - 如何在 r 中可视化 cox 模型中的交互?
- emacs - 如何通过 ALT-M 在 emacs 中进行编译?
- php - PHP更改行基于
- regex - 如何使用两种格式的正则表达式?
- javascript - 验证表单 hasError AngularJS
- python - openpyxl - 如何使用列号而不是字母?
- sql - 创建命令有什么错误,ErrorORA-00903: invalid table name and the FK reference to pk 是正确的?