使用美丽汤 4 Python 进行网络抓取

2024-04-24 15:08:39 发布

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

所以我刚开始用美丽的汤4,我遇到了一个问题,我试图解决了几天,但我不能。 让我先粘贴我要分析的html代码:

<table class="table table-condensed table-hover tenlaces tablesorter">
<thead>
<tr>
<th class="al">Language</th>
<th class="ac">Link</th>
</tr>
</thead>
<tbody>


            <tr>
            <td class="tdidioma"><span class="flag flag_0">0</span></td>
            <td class="tdenlace"><a class="btn btn-mini enlace_link" data-servidor="42" rel="nofollow" target="_blank" title="Ver..." href="LINK I WANT TO SAVE0"><i class="icon-play"></i>&nbsp;&nbsp;Ver</a></td>
            </tr>

            <tr>
            <td class="tdidioma"><span class="flag flag_1">1</span></td>
            <td class="tdenlace"><a class="btn btn-mini enlace_link" data-servidor="42" rel="nofollow" target="_blank" title="Ver..." href="LINK I WANT TO SAVE1"><i class="icon-play"></i>&nbsp;&nbsp;Ver</a></td>
            </tr>

            <tr>
            <td class="tdidioma"><span class="flag flag_2">2</span></td>
            <td class="tdenlace"><a class="btn btn-mini enlace_link" data-servidor="42" rel="nofollow" target="_blank" title="Ver..." href="LINK I WANT TO SAVE2"><i class="icon-play"></i>&nbsp;&nbsp;Ver</a></td>
            </tr>
</tbody>
</table>

正如您在每个<;tr>;中看到的,都有<;td>;语言和链接。问题是我不知道如何将语言与链接联系起来。我的意思是,我想选择,例如,如果语言中的空格是1,则返回链接。如果没有,什么也别做。但我只能用语言返回<;td>;,而不是所有的<;tr>;,这是重要的思想 我不知道我是不是说了我的观点,因为我真的不知道该怎么解释

我现在的代码从我的主url获取<;tbody>;,但我不知道如何实现这一点。在

谢谢,为我糟糕的英语道歉!在

编辑: 下面是我的代码示例,这样您就可以看到我正在使用的库以及所有内容

^{pr2}$

Tags: 代码ltgt语言tabletrclasstd
3条回答

试试这样的方法:

result = None
for row in soup.tbody.find_all('tr'):
    lang, link = row.find_all('td')
    if lang.string == '1':
        result = link.a['href']
print result

试着用这样的汤,也许你需要一些异常处理

trs = soup.select('tr') # here trs is a list of bs4.element.Tag type element

现在迭代列表

^{pr2}$

我假设您想检查URL是否包含1,如果包含,请保存它。这是你想要的吗?在

您可以尝试使用以下代码:

soup = BeautifulSoup(YOUR_TEXT_HERE)
tbody_soup = soup.find('tbody')
links = tbody_soup.find_all('a')
links_to_save = []

for item in links:
    print item.attrs['href'] # prints the url
    print item.get_text() # prints the text of the link
    print item.attrs # prints a dictionary with all the attributes

    # check if 1 is in url?
    if '1' in item.attrs['href']:
        links_to_save.append(item.attrs['href'])

print links_to_save

相关问题 更多 >