【问题标题】:How to locate td class in html code using python?如何使用 python 在 html 代码中定位 td 类?
【发布时间】:2018-11-01 06:31:05
【问题描述】:

我的 html 代码中有一个类。我需要使用 python 定位 td 类“Currentlocation”。

代码:

<td class="CURRENTLOCATION"><img align="MIDDLE" src="..\Images\FolderOpen.bmp"/> Metrics</td>

以下是我尝试过的代码。

第一次尝试:

My_result = page_soup.find_element_by_class_name('CURRENTLOCATION')

出现“TypeError: 'NoneType' object is not callable”错误。第二次尝试:

My_result = page_soup.find(‘td’, attrs={‘class’: ‘CURRENTLOCATION’})

得到“标识符中的无效字符”错误。

谁能帮我在 html 代码中使用 python 找到一个类?

【问题讨论】:

    标签: python html python-3.x web-scraping data-extraction


    【解决方案1】:
    from bs4 import BeautifulSoup
    sdata = '<td class="CURRENTLOCATION"><img align="MIDDLE" src="..\Images\FolderOpen.bmp"/> Metrics</td>'
    soup = BeautifulSoup(sdata, 'lxml')
    mytds = soup.findAll("td", {"class": "CURRENTLOCATION"})
    for td in mytds: 
        print(td)
    

    【讨论】:

    • 我在“soup1”中有一段 html 代码作为列表。知道如何将它作为 lxml 传递吗?我尝试了“soup1 = soup(myresult1, 'lxml')”,但它抛出了错误。你能帮我解决这个问题吗?
    • html 代码如何在列表中? ...应该是字符串吧?
    • [ 地点: 钦奈 , 说明: Place of stay ] 这是我输出的样例。不是列表吗?
    • @Jansirani 将所有列表数据转换为字符串并传递给BeautifulSoup 或将单个列表元素传递给BeautifulSoup,循环遍历列表元素
    • 谢谢,我把结果集转换成字符串,然后把它作为lxml传递给漂亮的汤。
    【解决方案2】:

    我试过你的代码,第二个例子,问题是你使用的引号。对我来说,它们是撇号(',unicode 代码点 \u2019),而 python 解释器需要单引号 (') 或双引号 (")。

    更改它们我可以找到标签:

    >>> bs.find('td', attrs={'class': 'CURRENTLOCATION'})
    <td class="CURRENTLOCATION"><img align="MIDDLE" src="..\Images\FolderOpen.bmp"/> Metrics</td>
    

    关于您的第一个示例。我不知道您在哪里找到对方法find_element_by_class_name 的引用,但它似乎不是由 BeautifulSoup 类实现的。相反,该类实现了__getattr__ 方法,这是一种特殊的方法,只要您尝试访问不存在的属性,就会调用该方法。这里是方法的摘录:

    def __getattr__(self, tag):
        #print "Getattr %s.%s" % (self.__class__, tag)
        if len(tag) > 3 and tag.endswith('Tag'):
            #
        # We special case contents to avoid recursion.
        elif not tag.startswith("__") and not tag == "contents":
            return self.find(tag)
    

    当您尝试访问属性find_element_by_class_name 时,您实际上是在寻找具有相同名称的标签。

    【讨论】:

      【解决方案3】:

      BeautifulSoup 中为此提供了一个功能。 您可以获得所有所需的标签并指定您在 find_all 函数中查找的属性。它返回满足条件的所有元素的列表

      import re
      from bs4 import BeautifulSoup 
      text = '<td class="CURRENTLOCATION"><img align="MIDDLE" src="..\Images\FolderOpen.bmp"/> Metrics</td>'
      soup = BeautifulSoup(text, 'lxml')
      output_list = soup.find_all('td',{"class": "CURRENTLOCATION"}) # I am looking for all the td tags whose class atrribute is set to CURRENTLOCATION 
      

      【讨论】:

      • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和文档链接。如果没有围绕它的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 2011-06-26
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多