Skip to main content
 首页 » 编程设计

python之BeautifulSoup .link.get ("href") 只返回 None

2025年02月15日36JustinYoung

在我的网络爬虫上使用 BeautifulSoup,出于某种原因,我的 links 变量返回了我指定的代码块,但是当我尝试获取“href”时,它只会吐出“None”。

from bs4 import BeautifulSoup 
import requests 
 
r = requests.get("https://www.kickstarter.com/discover/advanced?sort=most_funded") 
 
pageGrab = BeautifulSoup(r.content, "html.parser") 
 
#This comment below is another way I tried 
#for link in pageGrab.find_all("div", {"class" : "project-profile-title text-truncate-xs"}): 
 
links = pageGrab.find_all("div", {"class" : "project-profile-title text-truncate-xs"}) 
for link in links: 
    print (link.get("href")) 

如果我也在 reddit 上运行这个脚本,例如,有一些链接被抓取,但绝大多数结果是“无”。

这是我在页面上提取“href”的第一个目标

<a target="" href="/projects/getpebble/pebble-time-awesome-smartwatch-no-compromises?ref=most_funded">Pebble Time - Awesome Smartwatch, No Compromises</a> 

请您参考如下方法:

您正在选择 div 元素,它显然没有 href 属性。

您可以简化代码并使用 .select() method并直接定位子 a 元素:

links = pageGrab.select('.project-profile-title.text-truncate-xs a') 
for link in links: 
    print (link.get('href')) 

当然,您也可以使用现有代码并链接 .find() method在 div 元素之后;然而,这假设 div 元素将始终包含 a 元素,因此上面的代码使用起来会更安全。

divs = pageGrab.find_all("div", {"class" : "project-profile-title text-truncate-xs"}) 
for div in divs: 
    print (div.find('a').get("href")) 

此外,如果您想更进一步,.select() method接受大多数 CSS 选择器,这意味着您可以添加 [href] 属性选择器,以便仅选择具有 href 属性的子 anchor 元素:

links = pageGrab.select('.project-profile-title.text-truncate-xs a[href]') 
for link in links: 
    print (link.get('href'))