【问题标题】:How do I get this text residing within the tags using Beautiful Soup?如何使用 Beautiful Soup 获取位于标签内的文本?
【发布时间】:2019-11-08 00:42:11
【问题描述】:

我想从上面的代码中获取号码121。但是我得到的汤对象没有显示数字。

Link to my Image

    [<div class="open_pln" id="pln_1">
 <ul>
 <li>
 <div class="box_check_txt">
 <input id="cp1" name="cp1" onclick="change_plan(2,102,2);" type="checkbox"/>
 <label for="cp1"><span class="green"></span></label>
 </div>
 </li>
 <li id="li_open"><span>Desk</span> <br/></li>
 <li> </li>
 </ul>
 </div>]

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

你必须使用这样的汤找到所有li 属性 -

    attribute=req["li"]       
    all_links = soup.find_all(attribute)
    for link in all_links:
        print(link.text.strip())

【讨论】:

    【解决方案2】:

    开放式办公室的号码121 不在 HTML 代码中,而是在 JavaScript 中。您可以使用regex 提取它:

    import re
    import requests
    
    url ='https://www.coworker.com/search/los-angeles/ca/united-states'
    
    htmlpage = requests.get(url).text
    
    open_offices = re.findall(r'var openOffices\s*=\s*(\d+)', htmlpage)[0]
    private_offices = re.findall(r'var privateOffices\s*=\s*(\d+)', htmlpage)[0]
    
    print('Open offices: {}'.format(open_offices))
    print('Private offices: {}'.format(private_offices))
    

    打印:

    Open offices: 121
    Private offices: 40
    

    【讨论】:

    • 谢谢伙计。如果我可以在那里问几个问题。您是如何发现它在 JavaScript 中的?您是如何获得它们的代码的?
    • @PranavM 我在 Firefox 中查看了源代码并搜索了字符串 121。这个字符串唯一有意义的出现是在某个 Javascript 函数中,所以我从那里提取了它。
    【解决方案3】:

    没有re模块:

    import requests
    from bs4 import BeautifulSoup
    
    url ='https://www.coworker.com/search/los-angeles/ca/united-states'
    
    res = requests.get(url)
    soup = BeautifulSoup(res.text,"lxml")
    searchstr = "var openOffices = "
    script = soup.select_one(f"script:contains('{searchstr}')").text
    print(script.split(searchstr)[1].split(";")[0])
    

    输出:

    121
    

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2021-01-23
      • 2019-05-30
      • 2017-12-31
      相关资源
      最近更新 更多