【问题标题】:Get Contents from span(s) with id containing using BeautifulSoup使用 BeautifulSoup 从 id 包含的 span 中获取内容
【发布时间】:2016-03-19 18:03:28
【问题描述】:

我在使用 Beautiful Soup 4 从存储在 span 标签中的多个 html 文件中提取内容时遇到问题

我使用了 soupstrainer 和 find("dl") 将 html 缩减为带有 "dl" 标签的重复项,然后找到所有跨度。

我的问题是如何从每个跨度中提取正确的值并存储在一个变量中,以及如何处理

<span class="iconYes">Public</span>
<span class="iconNo">Private</span> 

所以我知道他们提供的服务

我的 Python 3 代码

WebText=BeautifulSoup(open(fileToProcess),"html.parser",parse_only=DentistStrainer)
datalist = WebText.find("dl")
        for listitems in datalist:
            spans = datalist.find_all('span')
            for span in spans:
                print(span)

样本输出

<span id="Content_Result_lblDentistName">Dr First Surname</span> 
<span class="lblAddress" id="Content_Result_lblAddress"><strong>Address</strong>: Dental Centre, Street, Town</span> 
<span class="lblAddress" id="Content_Result_lblPhone"><strong>Phone</strong>: 123-1234567</span> 
<span class="lblAddress" id="Content_Result_lblFax"><strong>Fax</strong>: 123-3456789</span> 
<span class="lblAddress" id="Content_Result_lblEmail">someone@somewhere.tld</span> 
<span class="lblAddress" id="Content_Result_lblWebsiteUrl">www.somewhere.tld</span> 
<span><strong>Services</strong>: </span> 
<span class="iconYes">Private</span> 
<span class="iconYes">Public</span>
<span class="iconNo">Credit Card</span>

我尝试使用提取值失败了

if span.contains("lblDentistName"):
   DentistName = span.text()
   print("Dentist ",DentistName)`

任何 Beautifulsoup 用户可以帮助我吗?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    使用CSS selectors:

    dentist_names = soup.select('dl span[id$="lblDentistName"]')
    for span in dentist_names:
        print(span.text())
    

    $= 选择以指定文本结束的属性。

    CSS选择器也可以用来查找所有class="icon.."span元素;它们按照它们在树中出现的顺序进行匹配:

    soup.select('dl span[class^="icon"]')
    

    ^= 匹配开头的类值(请注意,如果跨度有多个类,这可能不起作用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      相关资源
      最近更新 更多