Как получить доступ к значению href из элемента HTML div с помощью Python и Beautiful Soup?

#python #beautifulsoup

Вопрос:

Как получить доступ к ссылке из HTML divs?

Вот HTML то, что я пытаюсь наскрести, я хочу получить href значение:

 <div class="item-info-wrap">
<div class="news-feed_item-meta icon-font-before icon-espnplus-before"> <span class="timestamp">5d</span><span class="author">Field Yates</span> </div>
<h1> <a name="amp;amp;lpos=nfl:feed:5:news" href="/nfl/insider/story/_/id/31949666/six-preseason-nfl-trades-teams-make-imagining-deals-nick-foles-xavien-howard-more" class=" realStory" data-sport="nfl" data-mptype="story">
Six NFL trades we'd love to see in August: Here's where Foles could help, but it's not the Colts</a></h1>
<p>Nick Foles is running the third team in Chicago. Xavien Howard wants out of Miami. Let's project six logical deals.</p></div>

 

Вот код, который я пытался использовать для доступа к href значению:

 from bs4 import BeautifulSoup
import requests
source = requests.get('https://www.espn.com/nfl/team/_/name/phi/philadelphia-eagles').text
soup = BeautifulSoup(source, 'lxml')
for article in soup.find_all('div', class_='item-info-wrap'):
    headline = article.h1.a.text
    print(headline)
    summary = article.p.text
    print(summary)

    try:
        link_src = article.h1.a.href # Having difficulty getting href  value
        print(link_src)
        link = f'https://espn.com/{link_src}'

    except Exception as e:
        link = None

    print(link)


 

Результат, который я получаю, таков https://espn.com/None для каждой статьи ESPN. Ценю любую помощь и отзывы!

Ответ №1:

Если вы измените код в строке 12, как показано ниже, он должен работать.

 link_src = article.h1.a["href"]
 

К ВАШЕМУ СВЕДЕНИЮ https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes

Комментарии:

1. Спасибо за обратную связь. Это решило мою проблему, и я ценю документацию.