【问题标题】:Python html parsing using beautifulsoup framework使用beautifulsoup框架解析Python html
【发布时间】:2013-12-10 15:38:41
【问题描述】:

我正在使用 Beauitful Soup 框架来检索链接(来自以下 html 内容的引用)

         <div class="store">
               <label>Store</label>
                 <span>
                   <a title="Open in Google Play" href="https://play.google.com/store/apps/details?id=com.opera.mini.android" target="_blank">
                        <!-- ><span class="ui-icon app-store-gp"></span> -->
                        Google Play
                   </a><i class="icon-external-link"></i>
                 </span>
             </div>

我使用以下代码在 python 中检索它:

 pageFile = urllib.urlopen("appannie.com/apps/google-play/app/com.opera.mini.android")
 pageHtml = pageFile.read()
 pageFile.close()
 print pageHtml
 soup = BeautifulSoup("".join(pageHtml))
 item = soup.find("a", {"title":"Open in Google Play"})

 print item

我得到 NoneType 作为输出。任何帮助都会非常棒。

我打印了html页面,输出如下:

  <html>
  <head><title>503 Service Temporarily Unavailable</title></head>
  <body bgcolor="white">
  <center><h1>503 Service Temporarily Unavailable</h1></center>
  <hr><center>nginx</center>
  </body>
  </html>

在浏览器上运行良好

【问题讨论】:

  • "503 Service Temporarily Unavailable" 所以这不是 BeautifulSoup 问题,而是服务器问题...您确定您请求的页面正确吗?尝试设置一个像您的浏览器一样的通用用户代理,看看它是否仍然可以。

标签: python html beautifulsoup href


【解决方案1】:
item = soup.find("a", {"title":"Open in Google Play"})

您最初搜索的是标题为“在 Google Play 中打开”的“span”,但您要查找的元素是“a”(链接)。

编辑:由于服务器似乎返回 503 错误,请尝试使用此代码设置一个通用用户代理(未经测试,它可能根本不起作用;您需要import urllib2):

soup = BeautifulSoup(urllib2.urlopen(urllib2.Request(sampleURL, None, {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"})).read())
item = soup.find("a", {"title":"Open in Google Play"}) 
print item

我还删除了无用的"".join(pageHtml),因为 urllib2 已经返回字符串,所以不需要加入。

【讨论】:

  • appannie.com/apps/google-play/app/com.opera.mini.android 我也尝试过使用它。它似乎没有帮助。仍然得到 NoneType
  • 我尝试了上面发布的代码并获得了积极的结果。
  • @hyleaus 我已将代码编辑为我使用的代码。该链接在浏览器上完美打开。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2014-03-06
  • 2011-07-21
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多