首页 > 解决方案 > 使用beautifulsoup时遇到的困难

问题描述

我正在尝试抓取一些网站,但是在收集我想要的东西时遇到了一些困难:

import requests 

from bs4 import BeautifulSoup

import time 

from datetime import date, datetime, timedelta

url = 'https://cerbios.swiss/news-events/news/'

page = requests.get(url)

soup = BeautifulSoup(page.content,'html.parser')

    

results_date = soup.find(class_='entry-title')

print(results_date)

这是我拥有的代码,此代码的输出是:

<h3 class="entry-title">

<a href="https://cerbios.swiss/new-400-mhz-nmr-in-cerbios/" rel="bookmark" title="NEW 400 MHZ NMR IN 

CERBIOS">NEW 400 MHZ NMR IN CERBIOS</a>

</h3>

这很好,但我真正想要的是“href”,以便在输出中只包含 URL,我真的不知道该怎么做,我尝试了这一行: results_url = soup.find(class_='entry -tite')['href'] 但它不起作用,因为类 'entry-title' 没有“href”的东西。如果有人可以帮助我,那将是一个很大的乐趣。

标签: pythonweb-scrapingbeautifulsoup

解决方案


您正在尝试访问不存在href的元素上的属性。<h3>您可以继续使用find()来获取<a>元素或使用更具体的选择器。

soup.find(class_='entry-title').find('a')['href']

或者

soup.select_one('h3.entry-title a')['href']

推荐阅读