【问题标题】:How to use find_element_by_class_name when there are several values with the same class name?当有多个具有相同类名的值时如何使用find_element_by_class_name?
【发布时间】:2022-01-18 22:57:19
【问题描述】:

我是网络抓取的新手,遇到了两个问题。首先,当我尝试使用 find_element_by_class_name 时,我收到一个错误,即不推荐使用 find_element_by_* 命令。我遇到的另一个问题是我试图抓取的网站有多个值分配给同一个类。如何确保我从网站上检索到正确的信息?

s=Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=s)
driver.get("https://covidactnow.org/us/california-ca/county/sacramento_county/?s=26811580")
print(driver.title)

search = driver.find_element_by_class_name("sc-pAzCb jEBzr")
print(search)

第一张图片显示了我要检索的课程和内容。但正如第二个屏幕截图所示,同一个类在网站的不同部分存储不同的值。如何区分两者?

【问题讨论】:

  • 您无法区分这两个(或更多)事件。在您的示例 HTML 中,相同的类出现在相同的元素类型 (span) 中。您可能可以通过观察它们的顺序来确定哪个与您相关

标签: python web-scraping


【解决方案1】:

为什么不直接访问网页用来获取数据的 API?

您需要做的就是获取路径列表,例如https://data.covidactnow.org/snapshot/2688/v2/state/AL.timeseries.json 代表州或 https://data.covidactnow.org/snapshot/2688/v2/county/06067.timeseries.json 代表县。

您可以通过从https://covidactnow.org/static/js/main.bcbf2cb9.chunk.js剪切相关的JSON来获取州和县的路径列表

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多