【问题标题】:Parsing nested tags with BeautifulSoup and requests使用 BeautifulSoup 和请求解析嵌套标签
【发布时间】:2019-04-17 21:49:49
【问题描述】:

我是BeautifulSoup 的新手。我试图用requests 解析一个HTML 网页。我现在写的代码是:

import requests
from bs4 import BeautifulSoup

link = "SOME_URL"
f = requests.get(link)
soup = BeautifulSoup(f.text, 'html.parser')
for el in (soup.findAll("td",{"class": "g-res-tab-cell"})):
    print(el)
    exit

输出如下:

<td class="g-res-tab-cell">
    <div style="padding:8px;">
        <div style="padding-top:8px;">
            <table cellspacing="0" cellpadding="0" border="0" style="width:100%;">
                <tr>
                    <td valign="top">
                        <div itemscope itemtype="URL">
                            <table cellspacing="0" cellpadding="0" style="width:100%;">
                                <tr>
                                    <td valign="top" class="g-res-tab-cell" style="width:100%;">
                                        <div style="width:100%;padding-left:4px;">
                                            <div class="subtext_view_med" itemprop="name">
                                                <a href="NAME1-URL" itemprop="url">NAME1</a>
                                            </div>
                                            <div style="direction:ltr;padding-left:5px;margin-bottom:2px;" class="smtext">
                                                <span class="Gray">In English:</span> ENGLISH_NAME1
                                            </div>
                                            <div style="padding-bottom:2px;padding-top:8px;font-size:14px;text-align:justify;min-height:158px;" itemprop="description">DESCRIPTION1</div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                </tr>
            </table>
            <table cellspacing="0" cellpadding="0" border="0" style="width:100%;">
                <tr>
                    <td valign="top">
                        <div itemscope itemtype="URL">
                            <table cellspacing="0" cellpadding="0" style="width:100%;">
                                <tr>
                                    <td valign="top" class="g-res-tab-cell" style="width:100%;">
                                        <div style="width:100%;padding-left:4px;">
                                            <div class="subtext_view_med" itemprop="name">
                                                <a href="NAME2-URL" itemprop="url">NAME2</a>
                                            </div>
                                            <div style="direction:ltr;padding-left:5px;margin-bottom:2px;" class="smtext">
                                                <span class="Gray">In English:</span> ENGLISH_NAME2
                                            </div>
                                        </div>
                                        <div style="padding-bottom:2px;padding-top:8px;font-size:14px;text-align:justify;min-height:158px;" itemprop="description">DESCRIPTION2</div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</td>

现在我卡住了。我正在尝试解析每个块的NAMEDESCRIPTIONENGLISH_NAME。我想打印它们中的每一个,所以输出将是:

name = NAME1
en_name = ENGLISH_NAME1
description = DESCRIPTION1
name = NAME2
en_name = ENGLISH_NAME2
description = DESCRIPTION2

我尝试阅读文档,但找不到如何处理嵌套属性,尤其是没有classid 名称。据我了解,每个块都以&lt;table cellspacing="0" cellpadding="0" border="0" style="width:100%;"&gt; 开头。在每个块中,我应该找到具有itemprop="url" 的标签a 并获得NAME。然后在&lt;span class="Gray"&gt;In English:&lt;/span&gt; 中获取en_name 并在itemprop="description" 中获取description。但我觉得BeautifulSoup 做不到(或者至少很难做到)。如何解决?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您可以使用 soup.find_all 使用类 g-res-tab-cell 遍历每个 td

    from bs4 import BeautifulSoup as soup
    d = soup(content, 'html.parser').td.find_all('td', {'class':'g-res-tab-cell'})
    results = [[i.find('div', {'class':'subtext_view_med'}).a.text, i.find('div', {'class':'smtext'}).contents[1].text, i.find('div', {'itemprop':'description'}).text] for i in d]
    

    输出:

    [['NAME1', 'In English:', 'DESCRIPTION1'], ['NAME2', 'In English:', 'DESCRIPTION2']]
    

    编辑:来自链接:

    import requests
    from bs4 import BeautifulSoup as soup
    d = soup(requests.get('https://www.sratim.co.il/browsenewmovies.php?page=1').text, 'html.parser')
    movies = d.find_all('div', {'itemtype':'http://schema.org/Movie'})
    result = [[getattr(i.find('a', {'itemprop':'url'}), 'text', 'N/A'), getattr(i.find('div', {'class':'smtext'}), 'text', 'N/A'), getattr(i.find('div', {'itemprop':'description'}), 'text', 'N/A')] for i in movies]
    

    【讨论】:

    • 谢谢!出于某种原因,我得到一个错误。我的猜测是因为我不明白 content 应该是什么。应该是content = requests.get(link) 还是content = soup(f.text, 'html.parser').findAll("td",{"class": "g-res-tab-cell"})? (他们都失败了)。我显示的 html 不是我正在解析的完整 HTML
    • @vesii 是的,contentrequests.get(link).text 的结果。如果可能的话,你能把链接发布到你正在抓取的网站吗?谢谢。
    • 我切换到了SO聊天(希望你能在那里回答)
    【解决方案2】:

    这是另一种方式。由于所有电影都存在该信息,因此您应该有一个完整的结果集。

    from bs4 import BeautifulSoup as bs
    import requests
    import pandas as pd
    r = requests.get('https://www.sratim.co.il/browsenewmovies.php?page=1')
    soup = bs(r.content, 'lxml')
    names = [item.text for item in soup.select('[itemprop=url]')]  #32
    english_names = [item.next_sibling for item in soup.select('.smtext:contains("In English: ") span')]
    descriptions = [item.text for item in soup.select('[itemprop=description]')]
    results = list(zip(names, english_names, descriptions))
    df = pd.DataFrame(results, columns = ['Name', 'English_Name', 'Description'])
    print(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 2011-06-03
      • 1970-01-01
      • 2021-12-11
      • 2015-02-09
      相关资源
      最近更新 更多