繁体   English   中英

使用 -beautiful-soup 获取 python 表列中的 href 链接

[英]get the href link in table columns in python with -beautiful-soup

我有这个数据,你可以看到:

[<td><span></span></td>, <td><span></span></td>, <td><a class="cmc-link" href="/currencies/renbtc/"><span class="circle"></span><span>renBTC</span><span class="crypto-symbol">RENBTC</span></a></td>, <td><span>$<!-- -->61947.68</span></td>, <td><span></span></td>]

我想提取href链接,正如您在此处看到的/currencies/renbtc/

这是我的代码:

from bs4 import BeautifulSoup
import requests
try:
    r = requests.get('https://coinmarketcap.com/')
    soup = BeautifulSoup(r.text, 'lxml')

    
    table = soup.find('table', class_='cmc-table')
    for row in table.tbody.find_all('tr'):    
        # Find all data for each column
         columns = row.find_all('td')
         print(columns)
         
except requests.exceptions.RequestException as e:
    print(e)

但结果是整个列。

迭代列表中的<td> ,如果<td><a>if td.a ),则.get('href')td.a

from bs4 import BeautifulSoup
import requests
try:
    r = requests.get('https://coinmarketcap.com/')
    soup = BeautifulSoup(r.text, 'lxml')

    table = soup.find('table', class_='cmc-table')

    for row in table.tbody.find_all('tr'):
        # Find all data for each column
        columns = row.find_all('td')
        for td in columns:
            if td.a:
                print(td.a.get('href'))
                # theoretically for performance you can
                # break
                # here to stop the loop if you expect only one anchor link per `td`

except requests.exceptions.RequestException as e:
    print(e)

对包含<a>列中的元素进行操作,选择它并获取其href

link = columns[2].a['href']

例子

from bs4 import BeautifulSoup
import requests
try:
    r = requests.get('https://coinmarketcap.com/')
    soup = BeautifulSoup(r.text, 'lxml')

    
    table = soup.find('table', class_='cmc-table')
    for row in table.tbody.find_all('tr'):    
        # Find all data for each column
         columns = row.find_all('td')
         link = columns[2].a['href']
         print(link)
         
except requests.exceptions.RequestException as e:
    print(e)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM