【问题标题】:BeautifulSoup & Craiglist - Trouble getting data with identical attributes and structureBeautifulSoup 和 Craiglist - 无法获取具有相同属性和结构的数据
【发布时间】:2020-01-12 04:28:25
【问题描述】:

我无法抓取下面的 HTML,因为所有信息都存储在一个没有太大区别的结构中。

我想要一个地方来检索包含在具有 text = 'VIN:' 的 span 标签中的 b 标签,以及包含在具有 text = 'odometer:' 等的 span 标签中的 b 标签。

</p>
</div>
<p class="attrgroup">
<span><b>2001 PORSCHE 911</b></span>
<br/>
</p>
<p class="attrgroup">
<span>VIN: <b>WP0CA29961S653221</b></span>
<br/>
<span>fuel: <b>gas</b></span>
<br/>
<span>odometer: <b>46000</b></span>
<br/>
<span>paint color: <b>silver</b></span>
<br/>
<span>size: <b>sub-compact</b></span>
<br/>
<span>title status: <b>clean</b></span>
<br/>
<span>transmission: <b>manual</b></span>
<br/>
<span>type: <b>convertible</b></span>
<br/>
</p>
</div>

我尝试了以下变体但无济于事:

all = soup.find_all('section',{'class':'body'})
for i in all:
    print(i.find_all('span'))

&

all = soup.find_all('section',{'class':'body'})
for i in all:
     print(i.find_all('b'))

&

all = soup.find_all('section',{'class':'body'})
for i in all:
    print(i.find_all('p',{'class':'attrgroup'}))

字段是动态的,因此结构可以改变。例如,另一个列表可能没有里程表信息或燃料选项,因此将其分解为列表并按索引获取特定信息将不一致。

我如何成功地做到这一点?

【问题讨论】:

    标签: python selenium web-scraping beautifulsoup craigslist


    【解决方案1】:

    尝试类似这样的:

    from bs4 import BeautifulSoup
    
    html = """
    </p>
    </div>
    <p class="attrgroup">
    <span><b>2001 PORSCHE 911</b></span>
    <br/>
    </p>
    <p class="attrgroup">
    <span>VIN: <b>WP0CA29961S653221</b></span>
    <br/>
    <span>fuel: <b>gas</b></span>
    <br/>
    <span>odometer: <b>46000</b></span>
    <br/>
    <span>paint color: <b>silver</b></span>
    <br/>
    <span>size: <b>sub-compact</b></span>
    <br/>
    <span>title status: <b>clean</b></span>
    <br/>
    <span>transmission: <b>manual</b></span>
    <br/>
    <span>type: <b>convertible</b></span>
    <br/>
    </p>
    </div>
    """
    soup = BeautifulSoup(html,'html.parser')
    prefixes = ["VIN", "odometer"]
    for n in soup.find_all('p', attrs={'class': 'attrgroup'}):    
       for x in n.find_all('span'):
        if(x.text.startswith(tuple(prefixes))):
          print(x.find('b').text)    
    

    结果:

    WP0CA29961S653221
    46000
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2017-05-24
      • 1970-01-01
      • 2015-09-22
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多