我有這個資料,你可以看到:
[<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)
但結果是整個列。
uj5u.com熱心網友回復:
迭代<td>串列中的 ,如果<td>有<a>( if td.a),則.get('href')of 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)
uj5u.com熱心網友回復:
對包含 的列中的元素進行操作<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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344488.html
