获取网页内容(不是源代码)

时间:2016-09-18 06:50:28

标签: python python-2.7 web-scraping bs4

我想从here获取每天的降雨量数据。

当我在inspect mode时,我可以看到数据。但是,当我查看源代码时,我找不到它。

我正在使用urllib2BeautifulSoup from bs4

这是我的代码:

import urllib2
from bs4 import BeautifulSoup
link = "http://www.hko.gov.hk/cis/dailyExtract_e.htm?y=2015&m=1"

r = urllib2.urlopen(link)
soup = BeautifulSoup(r)
print soup.find_all("td", class_="td1_normal_class")
# I also tried this one
# print.find_all("div", class_="dataTable")

我得到一个空阵列。

我的问题是:如何获取页面内容,而不是页面源代码?

2 个答案:

答案 0 :(得分:3)

如果您打开chrome / firefox上的开发工具并查看请求,您会看到数据是从scons MONGO_VERSION=x.y.z MONGO_GITHASH=none ... 的请求生成的,该请求提供了您所有12个月的数据然后可以从中提取。

答案 1 :(得分:2)

如果在源代码中找不到div,则表示生成了您要查找的div。它可能是使用一些像Angular或只是JQuery的JS框架。如果要浏览呈现的HTML,则必须使用运行包含JS代码的浏览器。

尝试使用selenium

How can I parse a website using Selenium and Beautifulsoup in python?

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.hko.gov.hk/cis/dailyExtract_e.htm?y=2015&m=1')

html = driver.page_source
soup = BeautifulSoup(html)

print soup.find_all("td", class_="td1_normal_class")

然而请注意,使用Selenium可以减少这个过程,因为它必须拉动无头浏览器。

相关问题