【问题标题】:How do I access text from <a> tag with Beautifulsoup python如何使用 Beautifulsoup python 从 <a> 标签访问文本
【发布时间】:2021-09-13 12:43:34
【问题描述】:

我正在尝试通过 Beautifulsoup 访问来自 &lt;a&gt; 标记的文本。

我正在使用的页面:enter image description here

这是我的代码:

from bs4 import BeautifulSoup
import requests

def test():
    url = 'http://gsapqv1/qlikview/index.htm'
    page = requests.get(url)
    soup = BeautifulSoup(page.content,'html.parser')

    all_applications = []

    applications = soup.select('a.name')
    for app in applications:
        print(app.text)
    

test()

所以最后我想列出页面上所有应用程序的名称。

我是网络抓取的新手,我正在尝试学习教程,但我很难找到问题/解决方案。

【问题讨论】:

  • 嘿@Filpekann 欢迎来到SO!您在代码中提供的 URL 没有给出任何响应,您能否使用活动 URL 更新您的代码
  • @BhavyaParikh 哦,对不起。如何使我的 URL 处于活动状态?我尝试从不同的设备打开 URL 并且它有效。该 URL 应将您发送到此链接:i.stack.imgur.com/aKPIs.png

标签: python html web web-scraping beautifulsoup


【解决方案1】:

如果没有看到有效的 URL(无法访问此站点),我唯一可以建议的是 .select_one() bs4 方法,它只会抓取一个元素:

# grab text from <a> tag
>>> soup.select_one(".favorite.favOff").a.text
30 - Cap Rep calc.qvw
# grab URL from <a> tag
>>> soup.select_one(".favorite.favOff").a['href']
href link..

【讨论】: