【问题标题】:Cannot get the hyperlink href beautiful soup无法获取超链接href美汤
【发布时间】:2020-06-26 15:07:00
【问题描述】:

我正在尝试获取锚 (a) 元素的超链接,但我不断得到:

h ttps://in.finance.yahoo.com/h ttps://in.finance.yahoo.com/

我已经尝试了这里提供的所有解决方案:link

这是我的代码:

href_links = []
symbols = []
prices = []
commodities = []

CommoditiesUrl = "https://in.finance.yahoo.com/commodities"
r = requests.get(CommoditiesUrl)
data = r.text
soup = BeautifulSoup(data)

counter = 40
for i in range(40, 404, 14):
    for row in soup.find_all('tbody'):
        for srow in row.find_all('tr'):
            for symbol in srow.find_all('td', attrs={'class':'data-col0'}):
                symbols.append(symbol.text)
                href_link =  soup.find('a').get('href')
                href_links.append('https://in.finance.yahoo.com/' + href_link)
            for commodity in srow.find_all('td', attrs={'class':'data-col1'}):
                 commodities.append(commodity.text)
            for price in srow.find_all('td', attrs={'class':'data-col2'}):
                prices.append(price.text)


pd.DataFrame({"Links": href_links, "Symbol": symbols, "Commodity": commodities, "Prices": prices })

另外,我想知道与网站类似,在我的 pandas 数据框中将商品符号作为超链接是否可行。

【问题讨论】:

  • 最外层的for 循环到底是干什么用的? for i in range(40, 404, 14): i 甚至没有在循环体中引用

标签: python html beautifulsoup


【解决方案1】:

我不确定您发布的代码是怎么回事,但您可以通过 find 将属性 data-symbol 设置为 GC=Fa 元素简单地获取该 URL。 html 有 2 个这样的元素。你要的是第一个,就是soup.find('a', {'data-symbol': 'GC=F'}).get('href')返回的。

import requests, urllib

from bs4 import BeautifulSoup

CommoditiesUrl = "https://in.finance.yahoo.com/commodities"
r = requests.get(CommoditiesUrl)
data = r.text
soup = BeautifulSoup(data)

gold_href = soup.find('a', {'data-symbol': 'GC=F'}).get('href')

# If it is a relative URL, we need to transform it into an absolute URL (it always is, fwiw)
if not gold_href.startswith('http'):
    # If you insist, you can do 'https://in.finance.yahoo.com" + gold_href
    gold_href = urllib.parse.urljoin(CommoditiesUrl, gold_href)

print(gold_url)

另外,我想知道与网站类似,在我的 pandas 数据框中将商品符号作为超链接是否可行。

我不熟悉 pandas,但我会说答案是肯定的。见:How to create a table with clickable hyperlink in pandas & Jupyter Notebook

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2011-11-15
    • 2021-09-08
    • 1970-01-01
    • 2012-07-16
    相关资源
    最近更新 更多