【问题标题】:if else in FindAll using beautifulsoup如果在 FindAll 中使用 beautifulsoup
【发布时间】:2014-01-11 05:59:19
【问题描述】:

我正在尝试使用 bs4 抓取此 IP 地址。这里的ip是103.18.75.62

<div class="the-ip"><label id="a829266">1</label><label id="a814974">0</label><span id="a968168">3</span><label id="d735847">.</label><span id="d111988">1</span><span id="b284407">8</span><span id="b740896">.</span><label id="d817182">7</label><label id="e268019">5</label><span id="a721115">.</span><label id="e816439">6</label><span id="b903319">2</span></div>

我期待类似以下的工作

ip_div = soup.findAll('div' , class_ ='the-ip')
ips = ip[0].findAll('label' AND 'span')   // how to implement this AND ???
for i in ips:
    print i.get_text()

那么如何实现这个AND???

【问题讨论】:

    标签: beautifulsoup web-crawler


    【解决方案1】:

    使用 selectdiv.the-ip * 作为 css 选择器:

    >>> from bs4 import BeautifulSoup
    >>>
    >>> soup = BeautifulSoup('''
    ... <div class="the-ip">
    ...     <label id="a829266">1</label>
    ...     <label id="a814974">0</label>
    ...     <span id="a968168">3</span>
    ...     <label id="d735847">.</label>
    ...     <span id="d111988">1</span>
    ...     <span id="b284407">8</span>
    ...     <span id="b740896">.</span>
    ...     <label id="d817182">7</label>
    ...     <label id="e268019">5</label>
    ...     <span id="a721115">.</span>
    ...     <label id="e816439">6</label>
    ...     <span id="b903319">2</span>
    ... </div>
    ... ''')
    >>> ''.join(el.text for el in soup.select('div.the-ip *'))
    u'103.18.75.62'
    

    我认为div.the-ip&gt;*(或div.the-ip&gt;label, div.the-ip&gt;span)也应该可以工作。但这不适用于bs4。 (与 lxml 一起使用)

    回答问题how to implement this AND?

    你的意思是吗?

    您可以传递编译的正则表达式模式而不是字符串:

    >>> import re
    >>>
    >>> ip_div = soup.find('div' , class_='the-ip') # `find`, not `findAll` here.
    >>> ''.join(el.text for el in ip_div.findAll(re.compile('^(label|span)$')))
    u'103.18.75.62'
    

    ^(label|span)$ 匹配 labelspan

    【讨论】:

    • 像魅力一样工作......但我仍然想知道是否有办法在 FindAll 中实现“AND”
    • @suneet,我明白了。你的意思是?我更新了答案。
    • 哎呀。是的,或者......完美的答案:*
    猜你喜欢
    • 2017-01-21
    • 2021-11-21
    • 2012-05-18
    • 2013-10-21
    • 2013-06-12
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多