【问题标题】:Python BeautifulSoup4 getting string info from a tag inside h1 tagPython BeautifulSoup4从h1标签内的标签获取字符串信息
【发布时间】:2014-09-04 14:29:42
【问题描述】:

我试图获取a标签内的字符串信息,但a标签在h1标签内。

<h1 class="branded-page-header-title">
      <span class="qualified-channel-title ellipsized"><span class="qualified-channel-title-wrapper"><span dir="ltr" class="qualified-channel-title-text" ><a dir="ltr" href="/user/viralvideoslmao" class="spf-link branded-page-header-title-link yt-uix-sessionlink" title="ViralVideos" data-sessionlink="ei=lXIIVM-_CvKQigahpIHgDA"      >ViralVideos</a></span></span></span>
    </h1>

我想要在这种情况下为“ViralVideos”的信息 a.t.m 我有这个:

import requests
from bs4 import BeautifulSoup

def get_yt_links():
    url = "https://youtube.com"
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for code in soup.findAll('a'):
        href = "http://youtube.com" + code.get('href')
        if "channel/U" in href:
            get_user(href)
            print(href)

def get_user(url):
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for user in soup.findAll('h1', {'class': 'branded-page-header-title'}).a:
        print(user.string)

提前致谢

【问题讨论】:

    标签: html python-3.x tags beautifulsoup web-crawler


    【解决方案1】:

    您现在遇到的问题是findAll() 返回一个结果列表,而列表中没有a 属性。

    要获取a标签,可以使用CSS selectors并检查h1a标签的类名:

    soup = BeautifulSoup(data)
    for link in soup.select('h1.branded-page-header-title a.branded-page-header-title-link'):
        print link.text  
    

    对于您提供的 HTML,它会打印 ViralVideos

    【讨论】:

      【解决方案2】:

      只需将find_all 更改为find

      soup = BeautifulSoup(plain_text)
      print soup.find('h1', {'class': 'branded-page-header-title'}).a.text
      

      【讨论】:

      • 问题是——我们不知道h1 是否只有一个branded-page-header-title 类,也不知道里面有多少a 标签。 OP 提供的示例只是大图的一小部分。
      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 2018-10-29
      • 2023-01-12
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      相关资源
      最近更新 更多