python抓取省市區的資料並儲存到mysql中

2021-08-11 04:31:40 字數 1861 閱讀 2498

**如下:

# coding: utf-8

'''python 抓取網頁資料

需要預先安裝外掛程式

python -m pip install beautifulsoup4

python -m pip install lxml

'''import requests

from bs4 import beautifulsoup

import mysqldb

import traceback

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

url = ''

# url = ''

# headers必須加,否則返回狀態是404

headers =

html = requests.get(url, headers=headers)

if html.status_code != requests.codes.ok:

print('404')

else:

db = mysqldb.connect("192.168.2.190", "root", "12345678", "python", port=3306, charset="utf8")

cursor = db.cursor()

html.encoding = 'utf-8'

soup = beautifulsoup(html.text, 'lxml')

context = soup.find_all(class_='msonormal')

for index in range(9, len(context)):

idandname = str(context[index].get_text()).split(" ")

if len(idandname) == 2:

sql = "insert into province_city_county(pccid, pccname) values (%s,%s)"

param = (idandname[0], idandname[1])

try:

cursor.execute(sql, param)

db.commit()

print index

except exception, e:

db.rollback()

traceback.print_exc()

db.close()

注意事項:

1.需要事先安裝requires和bs4庫

2.資料庫插入的時候不能採用format佔位符,好像佔位符不能對中文進行轉碼,害我弄了好久

3.要保證**格式為utf8,sys encoding為utf8,資料庫表字段為utf8,否則可能出現亂碼錯誤,參考資料:

最後查詢資料庫結果為:

+——–+———————–+

| pccid | pccname |

+——–+———————–+

| 110000 | 北京市 |

| 110100 | 北京市市轄區 |

| 110101 | 北京市東城區 |

| 110102 | 北京市西城區 |

| 110103 | 北京市崇文區 |

| 110104 | 北京市宣武區 |

| 110105 | 北京市朝陽區 |

| 110106 | 北京市豐台區 |

| 110107 | 北京市石景山區 |

| 110108 | 北京市海淀區 |

+——–+———————–+

全國省市區資料SQL 省市區

drop table if exists provinces create table provinces id int 11 not null auto increment,provinceid varchar 20 not null,province varchar 50 not null,pr...

省市區詳細位址分離及省市區詳細資料庫

資源包含省市區位址分離演算法和省市區位址資料,需要省市區位址資料的朋友,直接去adsmsq.php檔案中提取。getads new getads ar getads getalladdress 安徽省阜陽市潁上縣南照鎮六里村 var dump ar 輸出結果 array 4 exit 直接呼叫這個方...

OC字典的使用省市區

大概思路就是這樣,下面是 部分。匯入省市區 nsstring str nsstring stringwithcontentsoffile users dllo desktop jeson jeson area.txt encoding nsutf8stringencodingerror nil 將省...