无法在beauthulsoup中链接find和find\u all

2024-10-01 09:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本关于美容的书和文件。他们都说我应该能够链接find/find_所有的方法,并使用下标从一个页面抓取中得到我想要的东西。情况似乎并非如此。考虑下表。在

<tr>
<td><span style="display:none;" class="sortkey">Dresser !</span><span class="sorttext">**<a href="/wiki/Louise_Dresser" title="Louise Dresser">Louise Dresser</a>**</span></td>
<td><span style="display:none;" class="sortkey">Ship !</span><span class="sorttext"><i><a href="/wiki/A_Ship_Comes_In" title="A Ship Comes In">A Ship Comes In</a></i></span></td>
<td><span style="display:none;" class="sortkey">Pleznik !</span><span class="sorttext">Mrs. Pleznik</span></td>
</tr>
<tr>
<td><span style="display:none;" class="sortkey">Swanson !</span><span class="sorttext"><a href="/wiki/Gloria_Swanson" title="Gloria Swanson">Gloria Swanson</a></span></td>
<td><i><a href="/wiki/Sadie_Thompson" title="Sadie Thompson">Sadie Thompson</a></i></td>
<td><span style="display:none;" class="sortkey">Thompson !</span><span class="sorttext">Sadie Thompson</span></td>
</tr>
<tr>
<th scope="row" rowspan="6" style="text-align:center"><a href="/wiki/1928_in_film" title="1928 in film">1928</a>/<a href="/wiki/1929_in_film" title="1929 in film">29</a><br />
<small><a href="/wiki/2nd_Academy_Awards" title="2nd Academy Awards">(2nd)</a></small></th>
<td style="background:#FAEB86"><b><span style="display:none;" class="sortkey">Pickford !</span><span class="sorttext">**<a href="/wiki/Mary_Pickford" title="Mary Pickford">Mary Pickford</a>**</span> <img alt="Award winner" src="//upload.wikimedia.org/wikipedia/commons/f/f9/Double-dagger-14-plain.png" width="9" height="14" data-file-width="9" data-file-height="14" /></b></td>

我需要抓取第一个嵌套在表中的元素,然后获取第一个元素。Lousie Dresser将是第一个数据点,其次是Gloria Swanson,然后是Mary Pickford。在

我原以为下面的话能让我到达目的地,但我错了,6个小时后我就完了。在

^{pr2}$

这不是我唯一尝试过的代码。我尝试过遍历行、表数据单元格,然后访问标记。我试着要求一个标签,然后重新登记出来,结果被告知我不能得到我想要的文本。当我尝试连锁操作(如上所述)时,最常见的错误是AttributeError: 'ResultSet' object has no attribute 'find'.订阅绝对不起作用,即使是在复制书籍示例时(go fig?!)。而且,我也有过进程自行中止,我不知道这是可能的。在

对于发生了什么事以及为什么一件本应如此简单的事情看起来是这样的事情,我们将不胜感激。在


Tags: nonetitlestyledisplaywikitrclasstd
1条回答
网友
1楼 · 发布于 2024-10-01 09:36:15
import requests
from bs4 import BeautifulSoup

def getActresses(URL):
    res = requests.get(URL)

    try:
        soup = BeautifulSoup(res.content, "lxml")
        table = soup.find("table", {"class":"wikitable sortable"})
    except AttributeError:
        print("Error creating/navigating soup object")

    tr = table.find_all("tr")

    for _tr in tr:
        td = _tr.find_all("td")
        for _td in td:
            a = _td.find_all("a")
            for _a in a:
                print(_a.text.encode("utf-8"))

getActresses("https://en.wikipedia.org/wiki/Academy_Award_for_Best_Actress")

使用text而不是get_text(),很抱歉,我使用了requests模块来演示

find_all方法总是返回一个列表,因此必须循环使用它

相关问题 更多 >