简体   繁体   中英

How to read tables from multiple webpages, and combine them with pandas?

I tried to web crawling using common for ~ loop twice.

I wanted the results to come out as below..

    Company  Title  Salary  Location  Start_date  End_date
0      A1
1      A2
2      A3
3      A4
4      A5
5      A6
.      .
.      .
.      .
6000 A6001

But my results were as follows...

    Company  Title  Salary  Location  Start_date  End_date
0      A1
1      A2
.      .
.      .
19     A20
20     A1
21     A2
.      .
.      .

Instead of getting each page, my result is the last page, repeated (ie A1~A20 was repeated 30 times).

I'm not certain what I'm doing wrong.

from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
from tqdm import tqdm
import datetime


df = pd.DataFrame(columns = ('Company', 'Title', 'Salary', 'Location', 'Start_date', 'End_date'))

for i in tqdm(range(30), mininterval = 1):
    df_list = list()
    for n in range(20):
        print("Now", i, n)
        page = i + 1
        URL ="http://www.sisuljob.com/employ/employ_01.htm?tb=1&sca=&stx1=&stx2=&stx3=&sfl1=&sfl2=&sfl3=&page=" + str(page)
        req = urlopen(URL)
        html = req.read()
        soup = BeautifulSoup(html, 'html.parser')
    
        df.loc[n] = [
            soup.select('.pd10_text > a')[2*n].text,
            soup.select('.pd10_text > a')[(2*n)+1].text,
            soup.select('.text_02 > a')[4*n].text,
            soup.select('.text_02 > a')[(4*n)+1].text,
            soup.select('.text_02 > a')[(4*n)+2].text,
            soup.select('.text_02 > a')[(4*n)+3].text,
        ]
        df_list.append(df)
    
    print(df_list)
df_all = pd.concat(df_list, ignore_index = True)


#To_excel with today string file name.
today_string = datetime.datetime.now().strftime('%y.%m.%d_%Hh%Mm%Ss')
df_all.to_excel('Sisuljob_Raw_Data_(' + today_string + ').xlsx')

Original Code

  • The issue with the original code is that dataframe df is an object that was created outside of the loop
  • Each time the loop iterates, a pointer to the dataframe object df is added to df_list
  • With every loop, df changes, therefore all df in df_list are the same, and change with each loop.
  • That issue can be resolved by changing df_list.append(df) to df_list.append(df.copy()) .

Use pandas.read_html

  • Lucky for you that entire page of html is marked with <table> , which can easily be read with pandas.read_html
    • The method reads each table into a list of dataframes
    • For these pages, the table you want, is and index 14
  • Each of the tables at index 14 will be added to a list and then all the dataframes will be combined with pandas.concat
import pandas as pd

# read the pages; 1 - 29 and append the table at index 14 to df_list
df_list = [pd.read_html(f'http://www.sisuljob.com/employ/employ_01.htm?tb=1&sca=&stx1=&stx2=&stx3=&sfl1=&sfl2=&sfl3=&page={page}')[14] for page in range(1, 31)]

# concat the list of dataframes
df = pd.concat(df_list)

# dropna columns and rows
df = df.dropna(axis=0, how='all').dropna(axis=1, how='all').reset_index(drop=True)

# add a column header
df.columns = ['Company', 'Title', 'Salary', 'Location', 'Start_date', 'End_date']

df

print(df.info())
[out]:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 580 entries, 0 to 579
Data columns (total 6 columns):
 #   Column      Non-Null Count  Dtype 
---  ------      --------------  ----- 
 0   Company     580 non-null    object
 1   Title       580 non-null    object
 2   Salary      580 non-null    object
 3   Location    579 non-null    object
 4   Start_date  580 non-null    object
 5   End_date    580 non-null    object
dtypes: object(6)
memory usage: 27.3+ KB

df.head(20)

|    | Company                 | Title                                                            | Salary    | Location   | Start_date   | End_date   |
|---:|:------------------------|:-----------------------------------------------------------------|:----------|:-----------|:-------------|:-----------|
|  0 | 문정현대지식산업센터    | 시설기사                                                         | 2800~2900 | 서울       | 2020-09-11   | 채용시까지 |
|  1 | 인성에스비엠            | 시설(영선)기사 구인                                              | 2600~2700 | 서울       | 2020-09-11   | 채용시까지 |
|  2 | IBS인더스트리           | 판교 신세계조선호텔 전기/소방 주임                               | 2900~3000 | 경기       | 2020-09-11   | 2020-09-25 |
|  3 | (주)맥서브              | 연합뉴스 빌딩                                                    | 2500~2500 | 서울       | 2020-09-11   | 채용시까지 |
|  4 | 힐스테이트암사APT       | 기전주임(격일제)                                                 | 3300~3300 | 서울       | 2020-09-11   | 2020-09-20 |
|  5 | 양재하이브랜드          | 전기주임(무제한선임)-직영                                        | 3700~3900 | 서울       | 2020-09-11   | 채용시까지 |
|  6 | 삼구 아이엔씨           | 강남 (대치동,논현동) 글래드 호텔 일근 기사 구함2 개지점          | 2500~2700 | 서울       | 2020-09-11   | 채용시까지 |
|  7 | 스마일게이트 홀딩스     | [스마일게이트 SPMC] 시설지원팀 전기/소방 안전관리자 모집         | 3200~3700 | 경기       | 2020-09-11   | 채용시까지 |
|  8 | 분당트라팰리스          | 시설전기 격일제                                                  | 3200~3300 | 경기       | 2020-09-11   | 채용시까지 |
|  9 | 주식회사 케이에스메이트 | 호텔 기계 주임 주간                                              | 2800~2800 | 서울       | 2020-09-11   | 채용시까지 |
| 10 | (주)조은시스템          | 시설                                                             | 3300~3400 | 서울       | 2020-09-11   | 채용시까지 |
| 11 | (주)이노서브비엠        | 스카이파크 대전1호점 전기팀장,시설기사 구인                      | 2800~3200 | 서울       | 2020-09-11   | 채용시까지 |
| 12 | (주)한결티엠에스        | 경기도 광주 관리소장 모집                                        | 3400~3600 | 경기       | 2020-09-11   | 2020-09-30 |
| 13 | 스마일게이트 홀딩스     | [스마일게이트 SPMC] 시설지원팀 전기/소방 관리 담당 (주임~대리급) | 2700~3000 | 경기       | 2020-09-11   | 채용시까지 |
| 14 | 스마일게이트 홀딩스     | [스마일게이트 SPMC] 시설지원팀 기계/설비 관리 담당 (주임/대리급) | 2700~3000 | 경기       | 2020-09-11   | 채용시까지 |
| 15 | (주)호리마이어          | 기전기사                                                         | 2400~2400 | 서울       | 2020-09-11   | 채용시까지 |
| 16 | 미소들의료재단          | 병원내 직영 시설관리 4교대 가능자 모집                           | 2700~2900 | 서울       | 2020-09-11   | 채용시까지 |
| 17 | 백상기업(주)            | 연2640 여의도 KB통합사옥 시설기사(전기파트)                      | 2600~2700 | 서울       | 2020-09-11   | 2020-09-14 |
| 18 | 백상기업(주)            | 월220 여의도 KB국민은행신사옥 건축주임 주5                       | 2600~2700 | 서울       | 2020-09-11   | 2020-09-11 |
| 19 | 백상기업(주)            | [월250/식사제공] 인하대생활관 기전기사 모집(전기산업기사)        | 3000~3000 | 인천       | 2020-09-11   | 2020-09-14 |

df.tail(20)

|     | Company                   | Title                                                                           | Salary    | Location   | Start_date   | End_date   |
|----:|:--------------------------|:--------------------------------------------------------------------------------|:----------|:-----------|:-------------|:-----------|
| 560 | (주)에프엠텍              | 시설관리                                                                        | 3200~3300 | 서울       | 2020-08-13   | 2020-08-31 |
| 561 | 주식회사 폴에이산업       | 오피스 건물 시설 주임                                                           | 2500~2500 | 서울       | 2020-08-13   | 채용시까지 |
| 562 | 토탈S.E.M시스템           | 롯데마트 서초점 시설관리                                                        | 2500~2600 | 서울       | 2020-08-13   | 채용시까지 |
| 563 | 리마크빌 영등포           | 시설주임 보일러,가스 선임필수                                                   | 3300~3400 | 서울       | 2020-08-13   | 채용시까지 |
| 564 | 위례오벨리스크            | 기전주임                                                                        | 3300~3300 | 경기       | 2020-08-13   | 채용시까지 |
| 565 | (주)고암                  | 방재기사                                                                        | 2500~2700 | 서울       | 2020-08-13   | 2020-08-25 |
| 566 | 압구정빌딩                | 기계실기사                                                                      | 3100~3200 | 서울       | 2020-08-13   | 채용시까지 |
| 567 | 서울농수산시장관리(주)    | (단기기간제근로자:일용직/시급:10,523) 시설파트단순노무종사원, 청소, 취사보조 등 | 1400~3000 | 서울       | 2020-08-13   | 채용시까지 |
| 568 | (주)아이비에스 인더스트리 | 신라스테이 광화문 시설기사모집                                                  | 2500~2600 | 서울       | 2020-08-13   | 채용시까지 |
| 569 | 지에스아이주식회사        | 고압가스 기능사 / 시설관리                                                      | 3000~3400 | 서울       | 2020-08-13   | 채용시까지 |
| 570 | 선재에이치알              | 전기주임 모집/일근                                                              | 2900~3000 | 서울       | 2020-08-12   | 채용시까지 |
| 571 | 한국주택시설관리(주)      | 상가관리소장                                                                    | 4000~4500 | 서울       | 2020-08-12   | 2020-08-14 |
| 572 | (주)삼구아이앤씨          | [삼구아이앤씨] 가톨릭대학교 시설기사 모집                                       | 2700~2800 | 경기       | 2020-08-12   | 2020-08-31 |
| 573 | 주식회사 큐원             | 기계기사 모집                                                                   | 2700~2700 | 서울       | 2020-08-12   | 채용시까지 |
| 574 | 백상기업(주)              | 월220이상 여의도 KB국민은행 방송기사(주임-대리) 모집 주5                        | 2600~2800 | 서울       | 2020-08-12   | 채용시까지 |
| 575 | ksnc                      | 기계기사 모집                                                                   | 2800~2900 | 서울       | 2020-08-12   | 채용시까지 |
| 576 | 아이비에스인더스트리      | 방재주임                                                                        | 2800~2900 | 서울       | 2020-08-12   | 채용시까지 |
| 577 | 성민종합사회복지관        | 시설안전관리인                                                                  | 2800~3000 | 서울       | 2020-08-12   | 2020-08-18 |
| 578 | (주)케이엠산업            | 전기기사(선임) 구인                                                             | 3600~3600 | 강원       | 2020-08-12   | 채용시까지 |
| 579 | 코오롱LSI(주)             | 시설(전기,소방/4교대)기사 채용모집 - 서울(여의도) FKI타워                       | 2700~2900 | 서울       | 2020-08-12   | 채용마감   |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM