python - 使用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”的东西。如果有人可以帮助我,那将是一个很大的乐趣。
解决方案
您正在尝试访问不存在href
的元素上的属性。<h3>
您可以继续使用find()
来获取<a>
元素或使用更具体的选择器。
soup.find(class_='entry-title').find('a')['href']
或者
soup.select_one('h3.entry-title a')['href']
推荐阅读
- google-sheets-api - Google 表格 v3 API 使用限制
- google-apps-script - 使用 SetValue 写入另一个电子表格失败,没有错误/异常
- python - 无法从 CSV 文件中读取数据并存储在字典中
- typescript - 打字稿:错误枚举无法将未定义转换为对象(枚举未定义)
- regular-language - 使用抽水引理证明常规语言的不规则性 - 错误在哪里
- sqlcl - Sqlcl - 错误消息 = java.library.path 中没有 ocijdbc18
- android - 从 Android 中的 Firebase Cloud Functions onCall 方法获取返回值的正确方法是什么?
- python - 当我尝试在 Tensorflow 中调整图像大小时,如何解决“TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32”
- c# - 如何使用 NJsonSchema 更改属性的类型
- html - 某些手机上的垂直图像会变成水平图像