【问题标题】:How can I add an html 'path' (tag) from BeautifulSoup as a class instance variable in python?如何将 BeautifulSoup 中的 html“路径”(标签)添加为 python 中的类实例变量?
【发布时间】:2019-03-14 18:04:10
【问题描述】:

我正在尝试使用 BeautifulSoup 处理从在线网站提取的 html 数据。我创建了一个类“网站”,其中有几个函数可以根据我的目标文本位的标题、类等实例变量解析 html 脚本。例如

class Websites:

    def __init__(self, url, header, class_):
        self.url = url
        self.header = header
        self.class_ = class_

    def html(self):
        url = self.url
        webpage = urlopen(url)
        page_html = webpage.read()
        webpage.close()
        page_soup = bs(page_html, 'html.parser')
        return page_soup

将这些变量(标头、类)转换为类中的实例变量很简单,但是我正在努力将一个变量转换为类实例变量。我相信在 BeautifulSoup 术语中它被称为“标签”。如果我在类的实例上调用上面显示的 html 函数,我会得到一个可以保存为变量 (page_soup) 的 html 文本块,我可以在其中添加一个标签,例如像这样:

page_soup.div.h1.p

这指定了我想要访问的 html 脚本的确切部分。有什么办法可以修改上面显示的类 init 函数,以便它可以接受输入,例如:

amazon = Websites(url = 'Amazon.co.uk', tag = '.div.h1.p')

并将其用作类方法中的实例变量,如 self.tag?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    以这种方式访问​​标签与使用 BeautifulSoup 的 find() 函数相同,它返回第一个匹配的标签。因此,您可以编写自己的函数来模拟这种方法,如下所示:

    from bs4 import BeautifulSoup
    
    def get_tag(tag, text_attr):
        for attr in text_attr.split('.'):
            if attr:
                tag = tag.find(attr)
    
        return tag
    
    
    html = """<html><h2>test1</h2><div><h1>test2<p>display this</p></h1></div></html>"""
    soup = BeautifulSoup(html, "html.parser")
    
    print(soup.div.h1.p)
    print(get_tag(soup, '.div.h1.p'))
    

    这将显示:

    <p>display this</p>
    <p>display this</p>
    

    另一种方法是使用.select() 函数,它返回匹配标签的列表:

    print(soup.select('div > h1 > p')[0])    
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 2022-06-27
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      相关资源
      最近更新 更多