【问题标题】:Extracting unordered list for a particular <div>: BeautifulSoup提取特定 <div> 的无序列表:BeautifulSoup
【发布时间】:2013-06-04 10:47:09
【问题描述】:

我正在抓取我的 Android 应用所需的 webpage。我想做的是从href 属性中提取国家。这与one 相同。

这是我的代码:

from bs4 import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.howtocallabroad.com/a.html")
soup = BeautifulSoup(html_page)
li = soup.select("ul > li > a")
for link in li:
    print link.get('href')

我遇到的问题是结果返回所有a 标记,包括来自其他divs 的标记

afghanistan/
albania/
algeria/
american-samoa/
andorra/
angola/
anguilla/
antigua/
argentina/
armenia/
aruba/
ascension/
australia/
austria/
azerbaijan/
codes.html  # not needed
nanp.html   # not needed
qa/         # not needed
forums/     # not needed

我想知道完成这项工作需要什么功能。我只想在&lt;div id="content"&gt; 中过滤hrefs。 docs 没有太多信息。

对不起,这是我第一次写python。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    使用findAll():

    >>> for i in soup.find('div',{'id':'content'}).findAll('a'):
    ...     print i['href']
    ... 
    afghanistan/
    albania/
    algeria/
    american-samoa/
    andorra/
    angola/
    anguilla/
    antigua/
    argentina/
    armenia/
    aruba/
    ascension/
    australia/
    austria/
    azerbaijan/
    

    soup.find('div',{'id':'content'}) 照它说的做。它找到具有contentid 的div 标签(&lt;div id="content"&gt; 将被匹配)。

    .findAll()...找到所有! 'a' 用作查找所有 a 标签的参数。它返回每个 a 标签的列表。

    然后我只需打印每个 a-tag 的 href

    【讨论】:

      【解决方案2】:

      试试

      li = soup.select("#content ul > li > a")
      

      而不是

      li = soup.select("ul > li > a")
      

      【讨论】:

        【解决方案3】:

        这样做:

        li = soup.select("#content ul > li > a")
        

        例如:

        li = soup.select("#[call india][1] ul > li > a")
        

        【讨论】:

          猜你喜欢
          • 2015-12-05
          • 2013-02-25
          • 1970-01-01
          • 2016-06-15
          • 2020-06-19
          • 2021-11-20
          • 1970-01-01
          • 1970-01-01
          • 2012-10-15
          相关资源
          最近更新 更多