【问题标题】:Beautiful Soup Page Source Error美丽的汤页面源错误
【发布时间】:2012-04-29 00:37:40
【问题描述】:

我正在尝试从此 usl 获取 html 源代码: http://books.google.com/books?id=NZlV0M5Ije4C&dq=isbn:0470284889

我使用了以下代码:

#!/usr/bin/env python

import urllib, urllib2, urlparse, argparse, re
from bs4 import BeautifulSoup

def getPageSoup(address):
    request = urllib2.Request(address, None, {'User-Agent':'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)'} )
    urlfile = urllib2.urlopen(request)
    page = urlfile.read()
    urlfile.close()
    print 'soup has been obtained!'
    return BeautifulSoup(page)

soup2 = getPageSoup(address)
metadata = soup2.findAll("metadata_row")#this content is present when viewing from the web browser

但是,soup2 中的 html 源代码看起来与 Google 图书页面中的源代码不太一样:

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html><head><title>Quantitative Trading: How to Build Your Own Algorithmic Trading Business - Ernie Chan - Google Books</title><script>(function(){function a(c){this.t={};this.tick=function(c,e,b){b=void 0!=b?b:(new Date).getTime();this.t[c]=[b,e]};this.tick("start",null,c)}var d=new a;window.jstiming={Timer:a,load:d};try{var f=null;window.chrome&amp;&amp;window.chrome.csi&amp;&amp;(f=Math.floor(window.chrome.csi().pageT));null==f&amp;&amp;window.gtbExternal&amp;&amp;(f=window.gtbExternal.pageT());null==f&amp;&amp;window.external&amp;&amp;(f=window.external.pageT);f&amp;&amp;(window.jstiming.pt=f)}catch(g){};})();
    </script><link href="/books/css/_9937a87cb2905e754d8d5e36995f224d/kl_about_this_book_kennedy_full_bundle.css" rel="stylesheet" type="text/css"/></head></html>

来自 urllib2 的 HTML 源代码和我的网络浏览器非常不同。如何获取正确的页面源?

谢谢!

【问题讨论】:

    标签: python web-crawler beautifulsoup urllib2


    【解决方案1】:

    这是正确的页面来源。页面的所有可见内容都是由 JavaScript 生成的。因此,使用 urllib 获取实际内容是不可能的。您应该使用浏览器扩展、webkit 绑定或类似的东西。

    【讨论】:

    • 谢谢!这很不方便,需要安装一个成熟的 JS 引擎和 QT 绑定。但都一样,我想没有别的办法了……
    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多