python - 使用 Beautiful Soup 从 td 元素中提取 URL

标签 python beautifulsoup

我正在尝试从 html 表中提取 URL。该 URL 位于 td 单元格内的 anchor 标记内。 html 看起来像:

<table width="100%" border="0" cellspacing="0" cellpadding="0" name="TabName" id="Tab" class="common-table">
    <tr>
        <td>Acme Company</a><br/><span class="f-10">07-11-2016</span></td>
        <td><span>Vendor</span><br>
        <td><a href="http://URL" title="Report Details">Details</a></td>
    </tr>
</table>

这是我编写的 Python 代码:

from bs4 import BeautifulSoup
import requests
import re

r = requests.get('http://SourceURL')
soup = BeautifulSoup(r.content,"html.parser")
# Find table
table = soup.find("table",{"class": "common-table"})
# Find all tr rows
tr = table.find_all("tr")

for each_tr in tr:
    td = each_tr.find_all('td')
    # In each tr rown find each td cell
    for each_td in td:
        print(each_td.text)
        if(each_td.text == "Details"):

我一直遍历到最后一个有 URL 的 td 标签。我现在如何提取 URL?

提前感谢您的宝贵时间。

最佳答案

像这样:

url = each_td.a['href']

关于python - 使用 Beautiful Soup 从 td 元素中提取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473919/

相关文章:

python - 使用函数从指定索引开始对 Python 中不同长度的列表求和

python - 使用 pip 安装 Beautiful Soup

python - 使用 beautifulSoup、Python 抓取 h3 和 div 标签中的文本

python - 使用 Python 解析网页的搜索结果

python - 'None' 是 Unicode 而不是 python sqlite3 中的 NoneType

python - 为什么 dict 对象在 python 中是不可散列的?

python - 最近的时间戳价格 - Python 中的数据结构准备好了吗?

python - 有没有更好的方法来抓取这些数据?

python - 如何从内部带有 <span> 的 <dt> 标签中获取文本?

python - 将 OpenCV 与 Tkinter 结合使用