1、requests.get/post(url,headers = headers, params = params/data=data)
#使用requests庫 根據(jù)網(wǎng)頁get或post請求(存在傳參的話get用params,post用data),得到一個Response對象
Response.text(打印文本)
Response.encoding(文本編碼)補充:decode()解碼:decode('gbk')把一個‘gbk’轉(zhuǎn)unicode編碼;encode()編碼:把unicode轉(zhuǎn)其他編碼
Response.content(以字節(jié)的方式訪問請求反應(yīng))
Response.status_code(響應(yīng)狀態(tài)碼)
2斋攀、xpath解析
from lxml import etree(導(dǎo)包)
html_page = etree.HTML(Response.content)
data = html_page.xpath('//select[@id="cx_province"]/option/@value')(xpath提取)
3自娩、bs4提取
from bs4 import BeautifulSoup(導(dǎo)包)
soup=BeautifulSoup(Response.content,‘lxml’)
links = soup.find_all('a',class_='')#查找所有clas=‘’的a標(biāo)簽
for? a in links:a.text(a標(biāo)簽下的文本)晤硕,a.get('href')(a標(biāo)簽的連接)
4挣柬、正則提取
惕虑。坟冲。。溃蔫。
5健提、json數(shù)據(jù)提取
json.loads()或者eval()
6、保存session對話訪問和代理ip訪問
def ip_sql():
#存入數(shù)據(jù)庫
db = MySQLdb.connect("192.168.201.91","root","123456","spidertools" )# 打開數(shù)據(jù)庫連接
cursor = db.cursor()# 使用cursor()方法獲取操作游標(biāo)
sql="SELECT * FROM proxyippool; "# 創(chuàng)建數(shù)據(jù)表SQL語句
cursor.execute(sql)
results = cursor.fetchall()# 獲取所有記錄列表
for row in results:
ip=row[0]+'://'+row[1]+':'+row[2]
ip_data.append(ip)
db.commit()
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
# return ip_data
def savesql_hotel(data,savepoint_name):
import sqlite3
? ? #創(chuàng)建數(shù)據(jù)庫sqlite3
? ? con=sqlite3.connect(savepoint_name)
? ? con.execute('''CREATE TABLE IF NOT? EXISTS data
? ? ? ? (
? ? ? ? hoteltype varchar(200) NOT NULL,
? ? ? ? -- province varchar(200) NOT NULL,
? ? ? ? city varchar(200) NOT NULL,
? ? ? ? name varchar(1000) DEFAULT NULL,
? ? ? ? address varchar(1000) DEFAULT NULL,
? ? ? ? salesTel varchar(100) DEFAULT NULL,
? ? ? ? lat varchar(100) DEFAULT NULL,
? ? ? ? lng varchar(100) DEFAULT NULL,
? ? ? ? Url? varchar(1000) DEFAULT NULL);''')
? ? # 插入數(shù)據(jù)
? ? sql='insert into data(hoteltype,city,name,address,salesTel,lat,lng,Url)\
? ? values("%s","%s","%s","%s","%s","%s","%s","%s")'%(u'',data[0],data[1],data[2],data[3],data[4],data[5],data[6])
? ? con.execute(sql)
? ? con.commit()
? ? con.close()
se = requests.session()
ip= random.sample(ip_data,1)[0]從得到的代理ip池中隨機取出一個
se.proxies = {'http': ip,'https': ip}
jstext=se.get('http://www.sicy......',headers=headers).content