python爬虫抓取信息_python爬虫爬取网上药品信息并且存入数据库
我最近在學習python爬蟲,然后正好碰上數(shù)據(jù)庫課設(shè),我就選了一個連鎖藥店的,所以就把網(wǎng)上的藥品信息爬取了下來。
1,首先分析網(wǎng)頁
2,我想要的是評論數(shù)比較多的,畢竟好東西大概是買的人多才好。然后你會發(fā)現(xiàn)它的url地址是有規(guī)律的里面的j1是指第一頁,j2第二頁,這樣構(gòu)建一個url_list。
1 url_list = ‘https://www.111.com.cn/categories/953710-a0-b0-c31-d0-e0-f0-g0-h0-i0-j%s.html‘#然后循環(huán)獲取響應
2
3 for i in range(1, 30):4
5 response = requests.get(url_list % i, headers=headers)
3,然后就可以進行數(shù)據(jù)的提取,我是利用Chrome的xpath插件,不過一定要注意有時候你復制的xpath不一定準確需要自己分析
我這里是演示提取價格,定位到價格選中后在Element里找到后點鼠標右鍵找到copy然后選擇copy xpath,上面那個黑框就是xpath插件
4,連接數(shù)據(jù)庫,我的數(shù)據(jù)庫是mysql的
連接數(shù)據(jù)庫的代碼一般是這樣
#!/usr/bin/python#-*- coding: UTF-8 -*-
importMySQLdb#打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost", "root", "123", "lianxi", charset=‘utf8‘)#使用cursor()方法獲取操作游標
cursor =db.cursor()#如果數(shù)據(jù)表已經(jīng)存在使用 execute() 方法刪除表。
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")#創(chuàng)建數(shù)據(jù)表SQL語句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )DEFAULT CHARSET =utf8"""cursor.execute(sql)#!/usr/bin/python#-*- coding: UTF-8 -*-
#打開數(shù)據(jù)庫連接
db = MySQLdb.connect("localhost", "root", "123", "lianxi", charset=‘utf8‘)#使用cursor()方法獲取操作游標
cursor =db.cursor()#SQL 插入語句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES (‘王‘, ‘Mohan‘, 20, ‘M‘, 2000)"""
try:#執(zhí)行sql語句
cursor.execute(sql)#提交到數(shù)據(jù)庫執(zhí)行
db.commit()except:#Rollback in case there is any error
db.rollback()print("a")#關(guān)閉數(shù)據(jù)庫連接
db.close()
這個我是參照菜鳥教程的https://www.runoob.com/python/python-mysql.html
5,最后把源碼附上,還有數(shù)據(jù)庫里爬取的數(shù)據(jù)
importrequestsfrom lxml importetreeimportpymysqldefget_text(text):iftext:returntext[0]return ‘‘
defcreate():
db= pymysql.connect("localhost", "root", "123", "lianxi",charset=‘utf8‘) #連接數(shù)據(jù)庫
cursor=db.cursor()
cursor.execute("DROP TABLE IF EXISTS a")
sql= """CREATE TABLE a (
ID INT PRIMARY KEY AUTO_INCREMENT,
藥物名字 char (255),
藥物價格 char (7),
藥物網(wǎng)址 CHAR(255),
藥店ID char (6) )DEFAULT CHARSET =utf8"""cursor.execute(sql)
db.close()
db= pymysql.connect("localhost", "root", "123", "lianxi",charset=‘utf8‘)
cursor=db.cursor()
url_list= ‘https://www.111.com.cn/categories/953710-a0-b0-c31-d0-e0-f0-g0-h0-i0-j%s.html‘headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"}for i in range(1, 30):
response= requests.get(url_list % i, headers=headers)
re=response.text
content=etree.HTML(re)
li_list= content.xpath(‘//ul[@id="itemSearchList"]/li‘)##單價,描述,評論數(shù)量,詳情頁鏈接
for li inli_list:#print(li)
price =get_text(li.xpath(‘.//div[@isrecom="0"]/p[1]/textarea/span/text()|.//div[@isrecom="0"]/p[1]/span/text()|.//div[@isrecom="0"]/p[1]/span/u/text()‘)).strip()
name= li.xpath(‘.//div[@isrecom="0"]/p[2]/a/text()‘)[1].strip()
url= get_text(li.xpath(‘.//div[@class="itemSearchResultCon"]/a[1]/@href‘)).strip()
infos=[]
item={}
item[‘價格‘] =price
item[‘名字‘] =name
item[‘地址‘] = ‘https:‘ +url
infos.append(item)print(item[‘價格‘])print(item[‘地址‘])print(item[‘名字‘])
a=1insert_sql= ‘INSERT INTO a (藥物價格,藥物名字,藥物網(wǎng)址,藥店ID) VALUES (%s,%s,%s,%s)‘cursor.execute(insert_sql, (item[‘價格‘],item[‘名字‘] ,item[‘地址‘],a))try:
db.commit()print(‘插入數(shù)據(jù)成功‘)except:
db.rollback()print("插入數(shù)據(jù)失敗")
db.close()if __name__ == ‘__main__‘:
create()
總結(jié):第一次寫博客,寫的很粗糙,代碼部分可能不是寫的很美,畢竟我也是個小白,希望大家多多留言,提提意見,一同進步。
原文:https://www.cnblogs.com/suqingjiu/p/12144132.html
總結(jié)
以上是生活随笔為你收集整理的python爬虫抓取信息_python爬虫爬取网上药品信息并且存入数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 影视这块怎么投
- 下一篇: python爬取晋江_[Arcpy] 爬