【问题标题】:Parse text from an href从 href 解析文本
【发布时间】:2014-08-28 00:12:27
【问题描述】:

我想从 href 解析文本。该网站的代码如下所示:

<ul class="ListSearches">
<li>
<a href="/example.com">Textiwant</a>
</li>

我尝试过类似的方法

from bs4 import BeautifulSoup
import requests

r  = requests.get("http://www.example.com")

data = r.text

soup = BeautifulSoup(data)

for ul in soup.find_all('li'):
    print(ul)

我得到这个输出

<li><button class="button grey" id="btnEurope">Europe</button></l <li><button class="button grey" id="btnAsia">Asia</button></li>

当我只想要来自 href 的文本时

【问题讨论】:

  • 我无法获取文本
  • 但实际发生了什么?你有错误吗?什么都没有打印?
  • 输出如下所示:
  • @Kenny94gulliUser: ul.get_text().
  • 它几乎可以工作我现在只得到文本而不是来自href的文本。
  • 标签: python parsing web beautifulsoup


    【解决方案1】:
    from bs4 import BeautifulSoup
    import requests
    
    r  = requests.get("http://www.example.com")
    
    data = r.text
    
    soup = BeautifulSoup(data)
    
    for ul in soup.find_all('li'):
        try:
            print ul.find_all("a")[0]['href']
        except:
            print "sorry Kenny94 gulliUser. this time soup failed  "
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签