我对编码很陌生,第一次使用stackoverflow.不知道我是否可以在这方面得到一些帮助.

我正在努力拼凑这个链接上给出的工作总数.

Following is my code.

import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

os.environ['PATH'] += "/Users/monicayadav/PycharmProjects/pythonProject4/selenium/venv/bin"
driver = webdriver.Firefox()
driver.implicitly_wait(30)


driver.get('https://jobs.bestbuy.com/bby?id=all_jobs&spa=1&s=req_id_num')
wait = WebDriverWait(driver, 10)
JobCountBESTBUY = wait.until(ec.presence_of_element_located((By.XPATH, "//p[contains(@class, 'font-wt-500 ng-binding')]"))).text

print(JobCountBESTBUY)

我得到的输出

jobs found

Process finished with exit code 0

结果我只找到了"找到工作",但我需要这个数字,而不是1925

推荐答案

解决方案1-更简单的解决方案

使用time.sleep(seconds)等待页面完全加载结果.它将是如下所示.别忘了import time.

import time

# ... Removed code for simplicity ...

driver.get('https://jobs.bestbuy.com/bby?id=all_jobs&spa=1&s=req_id_num')
time.sleep(10)
wait = WebDriverWait(driver, 10)
JobCountBESTBUY = wait.until(ec.presence_of_element_located((By.XPATH, "//p[contains(@class, 'font-wt-500 ng-binding')]"))).text

print(JobCountBESTBUY)

解决方案2-更快的解决方案

另一方面,time.sleep花了太多时间等待,即使文本已经准备好了.另一种方法是搜索文本本身,如下所示.优点是,一旦找到匹配项,等待就结束,可以直接返回数字.

import re

# ... Removed code for simplicity ...

driver.get('https://jobs.bestbuy.com/bby?id=all_jobs&spa=1&s=req_id_num')
WebDriverWait(driver, 10).until(ec.presence_of_element_located((By.XPATH, "//p[contains(@class, 'font-wt-500 ng-binding')]")))

# Matches `1,234`, `1`, `12`, `1,234,567`
r = re.compile(r'^([0-9,]+).*$')
JobCountBESTBUY = WebDriverWait(driver, 10).until(
  lambda _: (e := driver.find_element(By.XPATH, "//p[contains(@class, 'font-wt-500 ng-binding')]")) \
      and (m := r.match(e.text)) \
      and m.group(1)
)

print(JobCountBESTBUY)

Output

1,988

Python相关问答推荐

将标签移动到matplotlib饼图中楔形块的开始处

找到相对于列表索引的当前最大值列表""

从一个df列提取单词,分配给另一个列

用fft计算指数复和代替求和来模拟衍射?

仅使用预先计算的排序获取排序元素

通过对列的其余部分进行采样,在Polars DataFrame中填充_null`?

为什么在不先将包作为模块导入的情况下相对导入不起作用

我可以同时更改多个图像吗?

如何计算Pandas 中具有特定条件的行之间的天差

`Convert_time_zone`函数用于根据为极点中的每一行指定的时区检索值

将多行数据循环到嵌套框架中的单行

Python Curses Textbox.ather()删除空行,有没有办法保留它们?

在动态创建带有图像的按钮时遇到问题

在给定区间列表的情况下计算不重叠对的数量的最佳方法

导入pythoncom如何找到正确的文件?

自由空间里的激光...以及我如何才能检测到Line以进行进一步计算?

如何避免在PIL中绘制文本时创建透明部分?

如何reshape 极地数据帧?

Kivy:如何给浮动按钮(FloatLayout)添加on_Release方法?

有没有办法一次删除字典里的几个条目?