爬取网站:http://www.china-10.com/news/488659.html
代码以及注释如下:
import requests
from bs4 import BeautifulSoup
import re
import MySQLdb
#连接数据库
db = MySQLdb.connect("localhost","root","123456","lianxi",charset="utf8")
cursor = db.cursor()
#数据库中如果已经有china_population此表,则删除已存在的此表
cursor.execute("DROP TABLE IF EXISTS china_population")
#创建新表china_population
sql = r"""CREATE TABLE china_population (
rank INT(100) NOT NULL,
province CHAR(100) NOT NULL,
population INT(100) NOT NULL,
rise INT(100) NOT NULL)"""
cursor.execute(sql)
url = 'http://www.china-10.com/news/488659.html'
html = requests.get(url)
soup = BeautifulSoup(html.content,'html.parser')
#找到所有class为md_td的td元素
aaa = soup.find_all(name="td", attrs={"class":re.compile(r"md_td")})
#检查索引,以便于后面爬取工作
#for n,i in enume