提取 <a> 标签的内容

Extract content of <a> tag

我编写了代码,使用 BeautifulSoup 从页面中提取 url 和书名。

但它不是在 ></a> 标签之间提取书名 April Science April 1930

如何提取书名?

我尝试了另一个问题中推荐的 findnext 方法,但我得到了一个 AttributeError

HTML:

    <li>
        <a class="extiw" href="//www.gutenberg.org/ebooks/29390" title="ebook:29390">Astounding Stories of Super-Science April 1930</a>
        <a class="image" href="/wiki/File:BookIcon.png"><img alt="BookIcon.png" height="16" src="//www.gutenberg.org/w/images/9/92/BookIcon.png" width="16"/></a>
        (English)
    </li>

代码如下:

def make_soup(BASE_URL):
    r = requests.get(BASE_URL, verify = False)
    soup = BeautifulSoup(r.text, 'html.parser')
    return soup

def extract_text_urls(html):
    soup = make_soup(BASE_URL)

    for li in soup.findAll('li'):
        try:
            try:
                print li.a['href'], li.a['title']
                print "\n"
            except KeyError:
                pass
        except TypeError:
            pass

extract_text_urls(filename)

我没有看到您如何提取标签中的文本。我会做这样的事情:

from bs4 import BeatifulSoup as bs
from urllib2 import urlopen as uo
soup = bs(uo(html))

for li in soup.findall('li'):
    a = li.find('a')
    book_title = a.contents[0]
    print book_title

根据 the BeautifulSoup documentation 的说法,.string 属性 应该可以通过以下方式编辑您的原始列表来完成您想要做的事情:

    # ... 
        try:
            print li.a['href'], li.a['title']
            print "\n"
            print li.a.string
        except KeyError:
            pass
    # ... 

你可能想用类似

的东西包围它
if li.a['class'] == "extiw":
    print li.a.string

因为在您的示例中,只有 class extiw 的锚点包含书名。

感谢@wilbur 指出最佳解决方案。

要仅获取不在任何标签内的文本,请使用 get_text() 方法。它在文档 here.

我无法测试它,因为我不知道您要抓取的页面的 url,但您可以只使用 li 标签来完成,因为没有' 似乎是任何其他文本。

尝试替换这个:

    for li in soup.findAll('li'):
    try:
        try:
            print li.a['href'], li.a['title']
            print "\n"
        except KeyError:
            pass
    except TypeError:
        pass

有了这个:

    for li in soup.findAll('li'):
    try:
        print(li.get_text())
        print("\n")
    except TypeError:
        pass

您应该使用元素的 text 属性。以下对我有用:

def make_soup(BASE_URL):
    r = requests.get(BASE_URL)
    soup = BeautifulSoup(r.text, 'html.parser')
    return soup

def extract_text_urls(html):
    soup = make_soup(BASE_URL)

    for li in soup.findAll('li'):
        try:
            try:
                print li.a['href'], li.a.text
                print "\n"
            except KeyError:
                pass
        except TypeError:
            pass

extract_text_urls('http://www.gutenberg.org/wiki/Science_Fiction_(Bookshelf)')

我得到有关元素的以下输出

//www.gutenberg.org/ebooks/29390 Astounding Stories of Super-Science April 1930