【问题标题】:Get web page content (Not from source code) [duplicate]获取网页内容(不是来自源代码)[重复]
【发布时间】:2017-01-26 01:37:58
【问题描述】:

我想从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")

我得到了一个空数组。

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

【问题讨论】:

    标签: python python-2.7 web-scraping bs4


    【解决方案1】:

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

    尝试使用硒

    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 会显着减慢该过程,因为它必须启动无头浏览器。

    【讨论】:

      【解决方案2】:

      如果您打开 chrome/firefox 上的开发工具并查看请求,您会看到数据是从对 http://www.hko.gov.hk/cis/dailyExtract/dailyExtract_2015.xml 的请求生成的,它提供了所有 12 个月的数据,然后您可以从中提取.

      【讨论】:

      • 太酷了!我认为你的方法更有效。但是,@Simone Zandara 的答案更坚持这个问题,所以我选择它作为正确答案。
      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2021-02-17
      相关资源
      最近更新 更多