【问题标题】:Python WebScraper with BS4 and BeautifulSoup带有 BS4 和 BeautifulSoup 的 Python WebScraper
【发布时间】:2021-04-28 03:29:50
【问题描述】:

我正在尝试使用 BS4 创建一个抓取特定日期的网络爬虫。我能够构建 webscraper,但它拉错了日期。

我遇到的麻烦是他们共享同一个类,我尝试了 id 但我得到了 [] 的返回结果。我还能如何指定这个日期而不指定其他日期?

import requests
from bs4 import BeautifulSoup

URL = 'https://nemsis.org/state-data-managers/state-map-v3/colorado'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

date = soup.find('span',class_='state-updated-on')
date = date.text

print(date)  

它返回February 16, 2017,但我正在寻找09/04/2019

【问题讨论】:

  • 可以使用class和id吗?
  • 9/4/2019
  • 你不能使用find_all 来获取所有值 - 然后使用index - 即。 all_values[1] - 只得到一个你需要的值?

标签: python beautifulsoup


【解决方案1】:

页面是动态加载的,因此requests 不支持它。我们可以Selenium 来替代抓取页面。

安装它:pip install selenium

here下载正确的ChromeDriver。

from time import sleep
from selenium import webdriver
from bs4 import BeautifulSoup

URL = "https://nemsis.org/state-data-managers/state-map-v3/colorado"
driver = webdriver.Chrome(r"c:\path\to\chromedriver.exe")
driver.get(URL)
# Wait for the page to fully render
sleep(5)

soup = BeautifulSoup(driver.page_source, "html.parser")
print(soup.find("span", id="commitDate-refs/heads/release-3.4.0-3").text)

driver.close()

输出:

9/4/2019

【讨论】:

猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2015-05-30
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
相关资源
最近更新 更多