python--真气网城市空气质量数据抓取


红色框内的数据就是笔者需要的数据,使用selenium+python+chrome浏览器的方式抓取,这种方法比较简单,成功率很高,几乎没有什么阻碍。

chrome_options = Options()
chrome_options.add_argument('--headless')  ##设置浏览器不显示
prefs = {"profile.managed_default_content_settings.images": 2} ##禁止图片的加载,提升网页加载速度
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)  ## 模拟Chrome浏览器

driver.get('https://www.zq12369.com/?city=%s' % "北京")
# html = driver.page_source
aqi = driver.find_element_by_class_name('aqi').text
level = driver.find_element_by_xpath('/html/body/div[5]/div/div[10]').text
pollution = driver.find_element_by_class_name('pollution').text.split(":")[-1]
pdate = driver.find_element_by_class_name('pdate').text.split("时")[0].replace("年", "-").replace("月", "-").replace("日", " ") + ":00:00"

wrw1 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[1]/div[2]').text  ## PM2.5
wrw2 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[2]/div[2]').text  ## PM10
wrw3 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[3]/div[2]').text  ## SO2
wrw4 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[4]/div[2]').text  ## NO2
wrw5 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[5]/div[2]').text  ## CO
wrw6 = driver.find_element_by_xpath('/html/body/div[5]/div/div[13]/div[6]/div[2]').text  ## O3

这样所有的数据都已近抓取到了,接下来放在文本里保存和插入数据库都行。如有错误,欢迎指正,谢谢!

你可能感兴趣的:(python--真气网城市空气质量数据抓取)