【问题标题】:Parsing and extracting data to pandas using BeautifulSoup使用 BeautifulSoup 解析和提取数据到 pandas
【发布时间】:2018-08-01 09:17:28
【问题描述】:

我正在尝试从网站上抓取一些数据,但我是 Python/HTML 新手,需要一些帮助。

这是有效的代码部分:

from bs4 import BeautifulSoup
import requests
page_link ='http://www.some-website.com'
page_response = requests.get(page_link, timeout=5)
page_content = BeautifulSoup(page_response.content, "html.parser")
data = page_content.find(id='yyy')
print(data)

这成功抓取了我要抓取的数据,打印时显示如下

<div class="generalData" id="yyy">
<div class="generalDataBox">

<div class="rowText">
<label class="some-class-here" title="some-title-here">
Title Name
</label>
<span class="" id="">###</span>
</div>

<div class="rowText">
<label class="same-class-here" title="another-title-here">
Another Title Name
</label>
<span class="" id="">###2</span>
</div>

... more rows here ...

</div></div>

将其放入 pandas 数据框的最佳方法是什么?理想情况下,它将有两列:一列带有标签名称(即上面的“标题名称”或“另一个标题名称”),另一列带有数据(即上面的###和###2)。

谢谢!

【问题讨论】:

    标签: web-scraping beautifulsoup


    【解决方案1】:

    先提取部分:

    html = """<div class="generalData" id="yyy">
    <div class="generalDataBox">
    
    <div class="rowText">
    <label class="same-class-here" title="some-title-here">Title Name</label>
    <span class="" id="">###</span>
    </div>
    
    <div class="rowText">
    <label class="same-class-here" title="another-title-here">Another Title Name</label>
    <span class="" id="">###2</span>
    </div>"""
    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, 'html.parser')
    
    hashList = list()
    titleList = list()
    
    rangeLen = len(soup.find_all('label', class_="same-class-here"))
    
    for i in range(rangeLen):
        titleList.append(soup.find_all('label', class_="same-class-here")[i].get_text())
        hashList.append(soup.find_all('span')[i].get_text())
    

    现在,一旦您提取了您想要的任何内容,在本例中是两列的值,我们使用 pandas 将其放入数据框。

    import pandas as pd
    
    df = pd.DataFrame()
    df['Title'] = titleList
    df['Hash'] = hashList
    

    输出:

                    Title  Hash
    0          Title Name   ###
    1  Another Title Name  ###2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-29
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      相关资源
      最近更新 更多