【问题标题】:How to extract the href attribute value from an a tag with beautiful soup?如何从带有漂亮汤的a标签中提取href属性值?
【发布时间】:2020-06-24 04:02:27
【问题描述】:

这是我在平台上提取的 html 的一部分,它具有我想要获取的 sn-p,具有类“booktitle”的标签的 href 属性的值

</div>
<div class="elementList" style="padding-top: 10px;">
<div class="left" style="width: 75%;">
<a class="leftAlignedImage" href="/book/show/2784.Ways_of_Seeing" title="Ways of Seeing"><img alt="Ways of Seeing" src="https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1464018308l/2784._SY75_.jpg"/></a>
<a class="bookTitle" href="/book/show/2784.Ways_of_Seeing">Ways of Seeing (Paperback)</a>
<br/>
<span class="by">by</span>
<span itemprop="author" itemscope="" itemtype="http://schema.org/Person">
<div class="authorName__container">
<a class="authorName" href="https://www.goodreads.com/author/show/29919.John_Berger" itemprop="url"><span itemprop="name">John Berger</span></a>
</div>

使用 mechanize 库登录后,我有这段代码尝试提取它,但这里它返回代码要求的书名,我尝试了几种方法来仅获取 href 值,但没有一个有效远

from bs4 import BeautifulSoup as bs4
from requests import Session
from lxml import html
import Downloader as dw
import requests

def getGenders(browser : mc.Browser, url: str, name: str) -> None:
    res =  browser.open(url)
    aux = res.read()
    html2 = bs4(aux, 'html.parser')
    with open(name, "w", encoding='utf-8') as file2:
        file2.write( str( html2 ) )

getGenders(br, "https://www.goodreads.com/shelf/show/art", "gendersBooks.html")

with open("gendersBooks.html", "r", encoding='utf8') as file:
    contents = file.read()

    
    bsObj = bs4(contents, "lxml")

    aux = open("books.text", "w", encoding='utf8')

    officials  = bsObj.find_all('a', {'class' : 'booktitle'})

    for text in officials:
        print(text.get_text())
        aux.write(text.get_text().format())


    aux.close()
    file.close()

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

你可以试试这个吗? (对不起,如果它不起作用,我现在不在有 python 的电脑上)

for text in officials:
        print(text['href'])
       

【讨论】:

    【解决方案2】:

    BeautifulSoup 可以很好地与您提供的 html 代码配合使用,如果您想获取标签的文本,您只需使用“.text”,如果您想获取 href,请使用“.get('href') " 或者如果你确定标签有一个 href 值,你可以使用 "['href']"。

    这是一个简单的例子,用你的 html 代码片段很容易理解。

    from bs4 import BeautifulSoup 
    
    html_code = '''
    
    </div>
    <div class="elementList" style="padding-top: 10px;">
    <div class="left" style="width: 75%;">
    <a class="leftAlignedImage" href="/book/show/2784.Ways_of_Seeing" title="Ways of Seeing"><img alt="Ways of Seeing" src="https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1464018308l/2784._SY75_.jpg"/></a>
    <a class="bookTitle" href="/book/show/2784.Ways_of_Seeing">Ways of Seeing (Paperback)</a>
    <br/>
    <span class="by">by</span>
    <span itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <div class="authorName__container">
    <a class="authorName" href="https://www.goodreads.com/author/show/29919.John_Berger" itemprop="url"><span itemprop="name">John Berger</span></a>
    </div>
    
    '''
    
    soup = BeautifulSoup(html_code, 'html.parser')
    tag = soup.find('a', {'class':'bookTitle'})
    
    # - Book Title -
    title = tag.text 
    print(title)
    
    # - Href Link -
    href = tag.get('href')
    print(href) 
    

    我不知道你为什么下载了html保存到磁盘然后再次打开,如果你只是想获取一些标签值,那么下载html,保存到磁盘然后重新打开是完全没有必要的,你可以将html保存到一个变量中,然后将该变量传递给beautifulsoup。

    现在我看到您导入了 requests 库,但您使用了 mechanize,据我所知,requests 是在 python 中从网页获取数据时使用的最简单和最现代的库。我还看到您从请求中导入了“会话”,除非您想发出多个请求并希望保持与服务器的连接打开以加快后续请求的速度,否则不需要会话。

    此外,如果您使用“with”语句打开文件,则您使用的是 python 上下文管理器,它处理文件的关闭,这意味着您不必在最后关闭文件。

    所以你的代码更简化了,不用将下载的“html”保存到磁盘,我会这样。

    from bs4 import BeautifulSoup
    import requests
    
    url = 'https://www.goodreads.com/shelf/show/art/gendersBooks.html'
    
    html_source = requests.get(url).content 
    
    soup = BeautifulSoup(html, 'html.parser')
    
    # - To get the tag that we want -
    tag = soup.find('a', {'class' : 'booktitle'})
    
    # - Extract Book Title -
    href = tag.text
    
    # - Extract href from Tag -
    title = tag.get('href')
    

    现在,如果你有多个具有相同类名的“a”标签:('a', {'class' : 'booktitle'}),那么你可以这样做。

    首先获取所有的“a”标签:

    a_tags = soup.findAll('a', {'class' : 'booktitle'})
    

    然后抓取所有书籍标签信息并将每个书籍信息附加到书籍列表中。

    books = []
    for a in a_tags:
        try:
            title = a.text
            href = a.get('href')
            books.append({'title':title, 'href':href})  #<-- add each book dict to books list
            print(title)
            print(href)
        except:
            pass
    

    为了更好地理解您的代码,我建议您阅读以下相关链接:

    美汤: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

    请求: https://requests.readthedocs.io/en/master/

    Python 上下文管理器: https://book.pythontips.com/en/latest/context_managers.html

    https://effbot.org/zone/python-with-statement.htm

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多